Android Adapter usage Summary

Source: Internet
Author: User

Android Adapter usage Summary
Android Adapter usage Summary 1. the concept of Adapter is to transform an interface of a class into an interface that the client expects, so that the two classes that cannot work together due to interface mismatch can work together. In android, we can see that Adapter is an Adapter interface connecting back-end data and front-end display, and an important link between data and UI (View. Adapter is required in common View (List View, Grid View) 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 Base Adapter, Impleader, Adapter, Counteradaptation, etc.

 

  • 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. Example 1)ArrayAdapter

    The display of the list requires three elements:

    A. ListVeiw: displays the View of the list.

    B. Adapter: used to map data to the mediation on ListView.

    C. Data: The specific string, image, or basic component to be mapped.

    Example 1:

     

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

     

     

    Example 2:

     

    Public class MyListView extends Activity {private ListView listView; @ 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 ("scenario ");
             
    Data. add ("scenario ");
    Data. add ("scenario ");
    Data. add ("scenario ");
    Data. add ("scenario ");
    Data. add ("scenario ");
    Data. add ("scenario ");
    Data. add ("scenario ");
    Data. add ("scenario ");
    Return data ;}}
    The above Code uses Adapter (Context context, int resourcefulness, List
             
              
    Objects) to assemble data. to assemble the data, you need an Adapter connecting the List View object and array data to adapt the two. The structure of the Adapter requires three parameters, this 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, the adapter () is used to complete the final work of adaptation. As follows:
              

     

     

     

    2) SimpleAdapterSimpleAdapter 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. Implement ListView with icons

     

    1. Add a LisView component with the id of listView1 in main. xmlzhong.

     

                  
                
               

    2. Create a new layout file items. xml (horizontal layout)

     

    Add an ImageView component and a TextView component.

     

               
                   
                    
                 
                
               
    3. in the onCreate () method of the main Activity, first obtain the ListView added in the layout file, and then create two Arrays for saving the image id and text of the list items, add the image id and text to the List set, create a SimpleAdapter simple answer adapter, and associate the adapter with the ListView. The Code is as follows:

     

     

    @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); ListView listView = (ListView) findViewById (R. id. listView1); // get the list view int [] imageId = new int [] {R. drawable. img01, R. drawable. img02, R. drawable. img03, R. drawable. img04, R. drawable. img05, R. drawable. img06, R. drawable. img07, R. drawable. img08}; // defines the array String [] title = new String [] {"aaa", "bbb", "ccc", "ddd ", "eee", "fff", "ggg", "iii"}; // defines an array List for initializing and saving the text of the List item
               
                
    > ListItems = new ArrayList
                
                 
    > (); // Create a two-dimensional List array for (int I = 0; I
                 
                  
    Map = new Hashtable
                  
                   
    (); Map. put ("image", imageId [I]); // instantiate the map object map. put ("title", title [I]); listItems. add (map); // add the map object to the List set} SimpleAdapter adapter = new SimpleAdapter (this, listItems, R. layout. items, new String [] {"title", "image"}, new int [] {R. id. title, R. id. image}); // create SimpleAdapter listView. setAdapter (adapter); // associate the adapter with the ListView}
                  
                 
                
               
    Run:



     

    (SimpleAdapter Class Construction Method SimpleAdapter (Context context, List) > The context parameter in data, int resource, String [] from, int [] to) is used to specify the view context associated with SimpleAdapter running. The data parameter is used to specify a Map-based list, each entry in the list corresponds to a row in the list. The inresource parameter is used to specify a unique table for defining the view layout file of the list item (the newly created items ); the from parameter is used to specify an array of column names associated with each project on Map. The to parameter is used to specify an array of view IDs corresponding to the from display column parameter. 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 that you should not forget to add permissions to the AndroidManifest. xml file.
               

    4) BaseAdapter sometimes, the list is not only used for display, we can also add buttons on it. To add a button, you first need to write an xml file with a button. Then, you will naturally want to use the above method to define an adapter and map the data to the layout file. However, this is not the case because buttons cannot be mapped. Even if you have successfully displayed a button in the layout file, you cannot add a button response, in this case, we need to study how ListView is realistic and rewrite a class to inherit the BaseAdapter. The following example shows a button and an image. If you click a button, the row of the button is deleted. And tell you how the ListView works.
               
                   
                    
                         
                          
                       
                   
                  
                 
                 
                
               

    Public class MyListView4 extends ListActivity {private List
               
                
    > MData; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); mData = getData (); MyAdapter adapter = new MyAdapter (this); 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;} // logic of an item in ListView after selection @ Override protected void onListItemClick (ListView l, View v, int position, long id) {Log. v ("MyListView4-click", (String) mData. get (position ). get ("title");}/*** click the button in the listview to bring up the dialog box */public void showInfo () {new AlertDialog. builder (this ). setTitle ("My listvie W "). setMessage ("introduction... "). setPositiveButton ("OK", new DialogInterface. onClickListener () {@ Override public void onClick (DialogInterface dialog, int which ){}}). show ();}/** when Listie has a large amount of data to load, it will occupy a large amount of memory, affecting performance, in this case, you need to fill in and re-use view as needed to reduce object creation * the fastest way is to define a Pewholder and set the tag of convex to Pewholder, if it is not empty, use it again. */public final class ViewHolder {public ImageView img; public TextView title; public TextView info; pub Lic Button viewBtn;} public class MyAdapter extends BaseAdapter {private LayoutInflater mInflater; public MyAdapter (Context context) {this. mInflater = LayoutInflater. from (context) ;}@ Override public int getCount () {// TODO Auto-generated method stub return mData. size () ;}@ Override public Object getItem (int arg0) {// TODO Auto-generated method stub return null;} @ Override public long getItemI D (int arg0) {// TODO Auto-generated method stub return 0;} @ Override www.bkjia.com public View getView (int position, View convertView, ViewGroup parent) {ViewHolder holder = null; if (convertView = null) {holder = new ViewHolder (); convertView = mInflater. inflate (R. layout. vlist2, null); holder. img = (ImageView) convertView. findViewById (R. id. img); holder. title = (TextView) convertView. findViewById (R. id. title); holder.info = (TextView) convertView. findViewById (R.id.info); holder. viewBtn = (Button) convertView. findViewById (R. id. view_btn); convertView. setTag (holder);} else {holder = (ViewHolder) convertView. getTag ();} holder. img. setBackgroundResource (Integer) mData. get (position ). get ("img"); holder. title. setText (String) mData. get (position ). get ("title"); holder.info. setText (String) mData. get (p Osition ). get ("info"); holder. viewBtn. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {showInfo () ;}}); return convertView ;}}the above code is explained in detail below, when listView starts to draw, the system first calls the getCount () function, obtains the length of the listView based on its return value, and then calls 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.
                      
                     
                    
                   
                  
                 
                
               




     

     



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.