Usage of various adapters in Android

Source: Internet
Author: User

Usage of various adapters in Android

1. Concept

Adapter is an Adapter interface connecting back-end data and front-end display. It is an important link between data and UI (View. Adapter is required in common View (ListView, GridView) and other places. For example, the relationship among Data, Adapter, and View is intuitively expressed:

List of all adapters in Android:

The figure shows the complete hierarchy of all the interfaces and classes related to the Adapter in Android. During use, we can implement certain extensions of interfaces or inheritance classes according to our own needs. Commonly used include BaseAdapter, SimpleAdapter, ArrayAdapter, and SimpleCursorAdapter.

  • BaseAdapter is an abstract class that inherits from it and requires many methods, so it has high flexibility;
  • ArrayAdapter supports generic operations, which are the simplest and can only display one line of words.
  • SimpleAdapter has the best scalability and Can Customize various effects.
  • SimpleCursorAdapter can be used for simple text-only ListView. It requires the Cursor field to correspond to the UI id. You can rewrite other methods to implement a more complex UI. SimpleAdapter can be considered as a simple combination of databases, which can easily display the database content in the form of a list.

    2. Application Cases

    1)ArrayAdapter

    The display of the list requires three elements:

    A. ListVeiw is used to display the View of the list.

    B. the adapter is used to map data to the mediation on the ListView.

    C. The specific string, image, or basic component of the data to be mapped.

    Case 1

    Public class ArrayAdapterActivity extends ListActivity {@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // String [] strs = {"1", "2", "3", "4", "5"}; ArrayAdapter
       
        
    Adapter = new ArrayAdapter
        
         
    (This, android. R. layout. simple_expandable_list_item_1, strs); setListAdapter (adapter );}}
        
       

    Case 2

    Public class MyListView extends Activity {private ListView listView; // private List
       
        
    Data = new ArrayList
        
         
    (); @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); listView = new ListView (this); listView. setAdapter (new ArrayAdapter
         
          
    (This, android. R. layout. simple_expandable_list_item_1, getData (); setContentView (listView);} private List
          
           
    GetData () {List
           
            
    Data = new ArrayList
            
              (); Data. add ("test data 1"); data. add ("Test data 2"); data. add ("Test data 3"); data. add ("test data 4"); return data ;}}
            
           
          
         
        
       

    The above Code uses ArrayAdapter (Context context, int textViewResourceId, List Objects) to assemble the data. to assemble the data, you need an adapter connecting the ListView view object and the array data to adapt the two. The ArrayAdapter structure requires three parameters, which are this in turn, layout file (note that the layout file here describes the layout of each row in the list, android. r. layout. simple_list_item_1 is a layout file defined by the system that only displays one line of text, a data source (a List set ). At the same time, use setAdapter () to complete the final work of adaptation. As follows:

    2)SimpleAdapter
    SimpleAdapter has the best scalability. It can define various la S, put ImageView, Button, and CheckBox. The following code directly inherits the ListActivity. There is no big difference between ListActivity and common Activity. The difference is that the display ListView has been optimized and displayed.

    Case 1

    Simple. xml

       
       
        
        
       
    Public class SimpleAdapterActivity extends ListActivity {@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); SimpleAdapter adapter = new SimpleAdapter (this, getData (), R. layout. simple, new String [] {"title", "img"}, new int [] {R. id. title, R. id. img}); setListAdapter (adapter);} private List
       
        
    > GetData () {// map. put (parameter name, parameter value) List
        
         
    > List = new ArrayList
         
          
    > (); Map
          
           
    Map = new HashMap
           
            
    (); Map. put ("title", "Motorola"); map. put ("img", R. drawable. icon); list. add (map); map = new HashMap
            
              (); Map. put ("title", "Nokia"); map. put ("img", R. drawable. icon); list. add (map); map = new HashMap
             
               (); Map. put ("title", "Samsung"); map. put ("img", R. drawable. icon); list. add (map); return list ;}}
             
            
           
          
         
        
       

    Case 2
      The following program implements a class table with images. First, you must define an xml, vlist. xml, used to display the content of each column.

           
                  
                
                    
                     
                 
             
       
    public class MyListView3 extends ListActivity {        // private List
       
         data = new ArrayList
        
         ();        @Override        public void onCreate(Bundle savedInstanceState) {            super.onCreate(savedInstanceState);                 SimpleAdapter adapter = new SimpleAdapter(this,getData(),R.layout.vlist,                    new String[]{"title","info","img"},                    new int[]{R.id.title,R.id.info,R.id.img});            setListAdapter(adapter);        }             private List
         
          > getData() {            List
          
           > list = new ArrayList
           
            >();                 Map
            
              map = new HashMap
             
              (); map.put("title", "G1"); map.put("info", "google 1"); map.put("img", R.drawable.i1); list.add(map); map = new HashMap
              
               (); map.put("title", "G2"); map.put("info", "google 2"); map.put("img", R.drawable.i2); list.add(map); map = new HashMap
               
                (); map.put("title", "G3"); map.put("info", "google 3"); map.put("img", R.drawable.i3); list.add(map); return list; } }
               
              
             
            
           
          
         
        
       

    Data Using simpleAdapter is generally a List composed of HashMap. Each section of the list corresponds to each row of the ListView.Each key-value data of HashMap is mapped to the component corresponding to the id in the layout file. Because the system does not have a corresponding layout file available, we can define a layout vlist. xml. Next we will make adaptation. The new SimpleAdapter parameter is: this, layout file (vlist. xml), HashMap title, info, img. The component id, title, info, and img of the layout file. The components of the layout file are mapped to the elements of HashMap to complete adaptation.

    The running effect is as follows:

    3) SimpleCursorAdapter

    Public class SimpleCursorAdapterActivity extends ListActivity {@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // obtain a Cursor object pointing to the system Address Book database. Obtain the Data source: Cursor cur = getContentResolver (). query (People. CONTENT_URI, null, null); startManagingCursor (cur); // instantiate list adapter ListAdapter adapter = new SimpleCursorAdapter (this, android. r. layout. simple_list_item_1, cur, new String [] {People. NAME}, new int [] {android. r. id. text1}); setListAdapter (adapter );}}

    SimpleCursorAdapter can be used only when the database is used as the data source,Note: Do not forget to add permissions to the AndroidManifest. xml file.

       

    The effect is as follows:

    4) BaseAdapter <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Region + region + HTw8C01/bP1Mq + region + u1vdPDyc/region/b7d07PJ5LW9sry + region + 1s7EvP7P1Mq + s/region + region/region + s/region + cnZsaXN0Mi54bWw8L3A + Cgo8aW1nIHNyYz0 = "http://www.bkjia.com/uploads/allimg/140803/041Q35L4-2.gif" alt = "Copy code">

           
                
                 
                    
                     
                 
                
             
        


    /** 002 * @ author 003*004 */005 public class MyListView4 extends ListActivity {006 007 008 private List
        
         
    > MData; 009 010 @ Override011 public void onCreate (Bundle savedInstanceState) {012 super. onCreate (savedInstanceState); 013 mData = getData (); 014 MyAdapter adapter = new MyAdapter (this); 015 setListAdapter (adapter); 016} 017 018 private List
         
          
    > GetData () {019 List
          
           
    > List = new ArrayList
           
            
    > (); 020 021 Map
            
              Map = new HashMap
             
               (); 022 map. put ("title", "G1"); 023 map. put ("info", "google 1"); 024 map. put ("img", R. drawable. i1); 025 list. add (map); 026 027 map = new HashMap
              
                (); 028 map. put ("title", "G2"); 029 map. put ("info", "google 2"); 030 map. put ("img", R. drawable. i2); 031 list. add (map); 032 033 map = new HashMap
               
                 (); 034 map. put ("title", "G3"); 035 map. put ("info", "google 3"); 036 map. put ("img", R. drawable. i3); 037 list. add (map); 038 039 return list; 040} 041 042 // logic 043 @ Override044 protected void onListItemClick (ListView l, View v, int position, long id) {045 046 Log. v ("MyListView4-click", (String) mData. get (position ). get ("title"); 047} 048 049/** 050 * click the button in the listview pop-up dialog box 051 */052 public void showInfo () {053 new AlertDialog. builder (this) 054. setTitle ("My listview") 055. setMessage ("introduction... ") 056. setPositiveButton ("OK", new DialogInterface. onClickListener () {057 @ Override058 public void onClick (DialogInterface dialog, int which) {059} 060}) 061. show (); 062 063} 064 065 066 067 public final class ViewHolder {068 public ImageView img; 069 public TextView title; 070 public TextView info; 071 public Button viewBtn; 072} 073 074 075 public class MyAdapter extends BaseAdapter {076 077 private LayoutInflater mInflater; 078 079 080 public MyAdapter (Context context) {081 this. mInflater = LayoutInflater. from (context); 082} 083 @ Override084 public int getCount () {085 // TODO Auto-generated method stub086 return mData. size (); 087} 088 089 @ Override090 public Object getItem (int arg0) {091 // TODO Auto-generated method stub092 return null; 093} 094 095 @ Override096 public long getItemId (int arg0) {097 // TODO Auto-generated method stub098 return 0; 099} 100 101 @ Override102 public View getView (int position, view convertView, ViewGroup parent) {103 104 ViewHolder holder = null; 105 if (convertView = null) {106 107 holder = new ViewHolder (); 108 109 convertView = mInflater. inflate (R. layout. vlist2, null); 110 holder. img = (ImageView) convertView. findViewById (R. id. img); 111 holder. title = (TextView) convertView. findViewById (R. id. title); 112 holder.info = (TextView) convertView. findViewById (R.id.info); 113 holder. viewBtn = (Button) convertView. findViewById (R. id. view_btn); 114 convertView. setTag (holder); 115 116} else {117 118 holder = (ViewHolder) convertView. getTag (); 119} 120 121 122 holder. img. setBackgroundResource (Integer) mData. get (position ). get ("img"); 123 holder. title. setText (String) mData. get (position ). get ("title"); 124 holder.info. setText (String) mData. get (position ). get ("info"); 125 126 holder. viewBtn. setOnClickListener (new View. onClickListener () {127 128 @ Override129 public void onClick (View v) {130 showInfo (); 131} 132}); 133 134 135 return convertView; 136} 137 138} 139}
               
              
             
            
           
          
         
        

    The code above will be explained in detail below. When listView starts to be drawn, the system first calls the getCount () function, obtain the length of the listView Based on the returned value (this is why the list length is marked in the first figure at the beginning), and call getView () to draw each row one by one based on the length. If the returned value of getCount () is 0, the return 1 is not displayed in the list, and only one row is displayed.

    When the system displays the list, an adapter is first instantiated (the custom adapter will be instantiated here ). When manual adaptation is completed, data must be manually mapped. You need to override the getView () method. This method is called when every row in the list is drawn. GetView () has three parameters. position indicates the row to be displayed, and covertView indicates the layout from the layout file. We use the LayoutInflater method to extract the defined vlist2.xml file into a View instance for display. Then, instantiate each component in the xml file (simple findViewById () method ). In this way, the data can be mapped to each component. However, to respond to a click event, you need to add a click listener for the button to capture the click event. So far, a custom listView is complete. Now let's look back at this process. The system wants to draw the ListView. He first obtains the length of the list to be drawn, and then begins to draw the first line. How can he draw it? Call the getView () function. In this function, first obtain a View (actually a ViewGroup), then instance and set each component to display it. Now, we have drawn this line. Then draw the next line until the painting is complete. In the actual running process, it will be found that each row of the listView has no focus, because the Button grabs the focus of the listView, as long as the layout file sets the Button to no focus, it is OK.

    The effect is as follows:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.