Brief analysis on the adapter usage of Android _android

Source: Internet
Author: User
Tags stub

1. The concept

Adapter is an adapter interface that connects back-end data to the front-end display, and is an important link between data and the UI (View). In common view (Listview,gridview) and other places need to use adapter. The following figure visually expresses the relationship between data, Adapter and view:
All adapter in Android list:
From the diagram you can see all of the interfaces, classes, and adapter in Android. In our use of the process can be based on their own needs to implement interfaces or inherited classes to carry out a certain expansion. More commonly used are baseadapter,simpleadapter,arrayadapter,simplecursoradapter and so on.

    • Baseadapter is an abstract class, it needs to implement more methods, so it has high flexibility;
    • Arrayadapter supports generics operations, the simplest of which can only show a single line of words.
    • Simpleadapter has the best extensibility and can be customized to a variety of effects.
    • Simplecursoradapter can be applied to simple text-only ListView, which requires cursor field and UI IDs. You can also override other methods if you need to implement a more complex UI. Can be considered as a simple combination of simpleadapter database, you can easily put the contents of the database as a list of the form to display.

2. Application Cases

1) Arrayadapter

The display of the list requires three elements:

A Listveiw is used to show the view of the list.

b Adapters are used to map data to mediations on ListView.

C Data specific to the string, picture, or basic component that will be mapped.

Case A

public class Arrayadapteractivity extends Listactivity {
  @Override public
  void OnCreate (Bundle Savedinstancestate) {
   super.oncreate (savedinstancestate);
   The data for the list item
   string[] STRs = {"1", "2", "3", "4", "5"};
   arrayadapter<string> adapter = new Arrayadapter<string> (this,android. R.LAYOUT.SIMPLE_EXPANDABLE_LIST_ITEM_1,STRS);
   Setlistadapter (adapter);
  }
 

Case Two

 public class Mylistview extends activity {private ListView ListView;
  Private list<string> data = new arraylist<string> ();
    
   @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
   ListView = new ListView (this); Listview.setadapter New Arrayadapter<string> (this, Android.
   R.layout.simple_expandable_list_item_1,getdata ()));
  Setcontentview (ListView);
   Private List<string> GetData () {list<string> data = new arraylist<string> ();
   Data.add ("test data 1");
   Data.add ("Test Data 2");
   Data.add ("test Data 3");
    
   Data.add ("test data 4");
  return data; }
 }

The code above uses Arrayadapter (context, int textviewresourceid, list<t> objects) to assemble the data, To assemble this data requires an adapter that connects the ListView view object and array data to fit the two, and the Arrayadapter construct requires three parameters, sequentially this, the layout file (Note that the layout file here describes the layout of each row of the list, Android.) R.layout.simple_list_item_1 is a system-defined layout file that displays only one line of text, a data source (a list collection). At the same time use Setadapter () to complete the adaptation of the final work. The effect chart is as follows:

2) Simpleadapter

Simpleadapter is the best extensibility, you can define a variety of layouts, you can put a imageview (picture), you can put a button (buttons), checkboxes (check boxes) and so on. The following code is directly inherited listactivity,listactivity and ordinary activity is not too big difference, the difference is to show ListView do a lot of optimization, the aspect shows just.

Case A

Simple.xml

 <?xml version= "1.0" encoding= "Utf-8"?> <linearlayout "xmlns:android=" Schemas.android.com/apk/res/android "android:orientation=" vertical "android:layout_width=" Fill_parent "Android: layout_height= "Fill_parent" > <imageview android:id= "@+id/img" android:layout_width= "Wrap_content" Android: layout_height= "Wrap_content" android:layout_margin= "5DP"/> <textview android:id= "@+id/title" Android:layout_ Width= "Wrap_content" android:layout_height= "wrap_content" android:textcolor= "#ffffff" android:textsize= "20SP"/ > </LinearLayout> 
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<map<string, object>> GetData () {//map.put (parameter name, parameter value) list<map<string, OBJECT&G
   t;> list = new arraylist<map<string, object>> ();
   map<string, object> map = new hashmap<string, object> ();
   Map.put ("title", "Motorola");
   Map.put ("img", R.drawable.icon);
   
   List.add (map);
   Map = new hashmap<string, object> ();
   Map.put ("title", "Nokia");
   Map.put ("img", R.drawable.icon);
   
   List.add (map);
   Map = new hashmap<string, object> ();
   Map.put ("title", "Samsung");
   Map.put ("img", R.drawable.icon);
   List.add (map);
   return list;
 } 
  
 }

Case Two

The following procedure is to implement a class table with pictures. First you need to define a xml,vlist.xml that displays the contents of each column.

 <?xml version= "1.0" encoding= "Utf-8"?> <linearlayout "xmlns:android=" Schemas.android.com/apk/res/android "android:orientation=" horizontal "android:layout_width=" Fill_parent "Android: layout_height= "Fill_parent" > <imageview android:id= "@+id/img" android:layout_width= "Wrap_content" Android: layout_height= "Wrap_content" android:layout_margin= "5px"/> <linearlayout android:orientation= "vertical" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" > <textview android:id= "@+id/title" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:textcolor= "#FFFFFFFF" Android: Textsize= "22px"/> <textview android:id= "@+id/info" android:layout_width= "Wrap_content" android:layout_height = "Wrap_content" android:textcolor= "#FFFFFFFF" android:textsize= "13px"/> </LinearLayout> </linearlayou T> 
 public class MYLISTVIEW3 extends Listactivity {//private list<string> data = new arraylist<string> ();
  
   @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<map<string, object>> GetData () {list<map<string, object>> List = new Array
  
   List<map<string, object>> ();
   map<string, object> map = new hashmap<string, object> ();
   Map.put ("title", "G1");
   Map.put ("info", "Google 1");
   Map.put ("img", R.DRAWABLE.I1);
  
   List.add (map);
   Map = new hashmap<string, object> ();
   Map.put ("title", "G2");
   Map.put ("info", "Google 2");
   Map.put ("img", R.DRAWABLE.I2);
  
   List.add (map);
   Map = new hashmap<string, object> (); Map.put ("title", "G3 ");
   Map.put ("info", "Google 3");
   Map.put ("img", R.DRAWABLE.I3);
    
   List.add (map);
  return list;
 }
 }

Each section of the list,list that uses simpleadapter data in a hashmap composition is corresponding to each row of the ListView. Each key value data for the HashMap is mapped to the component of the corresponding ID in the layout file. Because the system does not have a corresponding layout file available, we can define a layout vlist.xml ourselves. Here is the adaptation, new one simpleadapter parameter is: this, layout file (vlist.xml), HashMap title and info,img. The component id,title,info,img of the layout file. The components of the layout file are mapped to the elements of the HashMap, and the matching is completed.

The results of the operation are shown below:

3) Simplecursoradapter

public class Simplecursoradapteractivity extends Listactivity {
  @Override public
  void OnCreate (Bundle Savedinstancestate) {
   super.oncreate (savedinstancestate);
   Get a Cursor object that points to the system Address Book database to obtain the data source
   Cursor cur = getcontentresolver (). query (People.content_uri, NULL, NULL, 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);
  }
 

Be sure to use the database as a data source when you need Simplecursoradapter, and here's a special note: Don't forget to add permissions to the Androidmanifest.xml file

<uses-permission android:name= "Android.permission.READ_CONTACTS" ></uses-permission>

The effect is as follows:

4) Baseadapter

Sometimes the list is not just for display purposes, but we can also add buttons to it. Add a button to first write a button XML file, and then naturally think of the above method to define an adapter, and then map the data to the layout file. But this is not the case, because the button is not mapped, even if you successfully use the layout file to display a button can not add a button response, it is necessary to study how ListView is realistic, and must rewrite a class to inherit baseadapter. The following example displays a button and a picture, and two lines of text if the click button deletes the row of the button. And tell you how ListView actually works.

Vlist2.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= "http://schemas.android.com/apk/res/" Android "android:orientation=" horizontal "android:layout_width=" Fill_parent "android:layout_height=" Fill_parent " > <imageview android:id= "@+id/img" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:layout_margin= "5px"/> <linearlayout android:orientation= "vertical" android:layout_width= "WRAP_" Content "android:layout_height=" wrap_content "> <textview android:id=" @+id/title "android:layout_width=" Wrap_ Content "android:layout_height=" wrap_content "android:textcolor=" #FFFFFFFF "android:textsize=" 22px "/> <textv Iew android:id= "@+id/info" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android: Textcolor= "#FFFFFFFF" android:textsize= "13px"/> </LinearLayout> <button android:id= "@+id/view_btn" Andr Oid:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:text= "@string/s_view_btn" android:layout_gravity= "Bottom|right"/> </LinearLayout>
 
/** * @author * */public class MyListView4 extends Listactivity {private list<map<string, OBJECT&GT;&G T
  
  Mdata;
   @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
   Mdata = GetData ();
   Myadapter adapter = new Myadapter (this);
  Setlistadapter (adapter); Private list<map<string, object>> GetData () {list<map<string, object>> List = new Arrayl
 
   Ist<map<string, object>> ();
   map<string, object> map = new hashmap<string, object> ();
   Map.put ("title", "G1");
   Map.put ("info", "Google 1");
   Map.put ("img", R.DRAWABLE.I1);
 
   List.add (map);
   Map = new hashmap<string, object> ();
   Map.put ("title", "G2");
   Map.put ("info", "Google 2");
   Map.put ("img", R.DRAWABLE.I2);
 
   List.add (map);
   Map = new hashmap<string, object> ();
   Map.put ("title", "G3");
   Map.put ("info", "Google 3");
   Map.put ("img", R.DRAWABLE.I3);
 List.add (map);  
   return list;
   
   The logical @Override protected void Onlistitemclick (ListView l, View v, int position, long ID) of an item selected in//ListView
  LOG.V ("Mylistview4-click", (String) mdata.get (position). Get ("title"); /** * ListView Click the button Pop-up dialog box * * public void Showinfo () {new Alertdialog.builder (). Settitle ("My ListView "). Setmessage (" Introduction ... "). Setpositivebutton (" OK ", new Dialoginterface.onclicklistener () {@Override public vo
   
  ID OnClick (dialoginterface dialog, int which) {}}). Show ();
   Public final class viewholder{public imageview img;
   Public TextView title;
   public TextView info;
  Public Button viewbtn;
   
   
   public class Myadapter extends baseadapter{private layoutinflater minflater;
   Public Myadapter {this.minflater = Layoutinflater.from (context);
   @Override public int GetCount () {//TODO auto-generated a stub return mdata.size (); }
 
   @Override public Object getitem (int arg0) {//TODO auto-generated a stub return null;
   @Override public long Getitemid (int arg0) {//TODO auto-generated method stub return 0; @Override public View getview (int position, View Convertview, ViewGroup parent) {Viewholder holder = n
    ull; 
     
     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 (position). Get ("info");
      Holder.viewBtn.setOnClickListener (New View.onclicklistener () {@Override public void OnClick (View v) {    
     Showinfo ();
    
    
    }
    });
   return convertview;
 }
   
  }  
 }

The following is a detailed explanation of the above code, ListView at the beginning of the draw, the system first calls the GetCount () function, according to his return is worth to the ListView length (this is also why the first figure in the beginning of the special marked list length), and then according to this length, Call GetView () to draw each row individually. If your GetCount () returns a value of 0, the list will not show the same return 1, showing only one row.

When the system displays a list, it first instantiates an adapter (this will instantiate the custom adapter). When you manually complete the adaptation, you must manually map the data, which requires overriding the GetView () method. This method is called when the system draws each row of the list. GetView () has three parameters, position represents the row to be displayed, and Covertview is the layout inflate from the layout file. We use the Layoutinflater method to extract the defined Vlist2.xml file into a view instance for display. The individual components in the XML file are then instantiated (a simple Findviewbyid () method). This allows the data to be mapped to individual components. But in response to the Click event, the button needs to add a click listener for it to capture the click event. Now that a custom ListView is done, let's go back and look at the process. System to draw ListView, he first obtained the length of the list to be drawn, and then began to draw the first line, how to draw it? Call the GetView () function. In this function you first get a view (actually a viewgroup), and then instantiate and set up each component to display it. All right, I've finished drawing this line. Then draw the next line until the painting is finished. In the actual run, you will find that each row of ListView has no focus, because the button robs the focus of the ListView, as long as the button is set to no focus in the layout file.

The effect is as follows:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.