"Side doing project learning Android" Knowledge Point: Adapter Adapter

Source: Internet
Author: User

1. 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. such as the intuitive expression of data, Adapter, view the relationship between the three:

All adapter at a glance in Android:

The graph can see the full hierarchy of all the interfaces and classes related to adapter in Android. In our use of the process can be implemented according to their own requirements of the interface or inheritance class to some extent. More commonly used are baseadapter,simpleadapter,arrayadapter,simplecursoradapter and so on.

    • Baseadapter is an abstract class, inheriting it needs to implement more methods, so it also has a high degree of flexibility ;
    • Arrayadapter supports generic operations, the simplest of which is to display only one line of words .
    • Simpleadapter has the best extensibility and can customize various effects.
    • Simplecursoradapter can be applied to a simple text-only ListView, which requires the cursor's field and UI ID to correspond. You can 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 in the form of a list to display.
2. Application Case 1) Arrayadapter

The display of a list requires three elements:

A Listveiw The view used to display the list.

b The adapter is used to map data to mediations on the ListView.

C The data is specific to the string, picture, or base component that will be mapped.

Case One

public class Arrayadapteractivity extends Listactivity {     @Override public     void OnCreate (Bundle Savedinstancestate) {         super.oncreate (savedinstancestate);         Data for list items         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<s            Tring> ();            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<t> objects) to assemble the data, To assemble this data requires an adapter that connects the ListView object and array data to fit the two, and the Arrayadapter construct requires three parameters, the 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 final work of adaptation. As follows:

2) Simpleadapter

Simpleadapter is the best extensibility, you can define a variety of layouts, you can put on imageview (picture), you can also put a button (button), CheckBox (check box) and so on. The following code directly inherits the listactivity,listactivity and the normal activity is not much different, the difference is to display the ListView did a lot of optimization, the aspect shows just.

Case One

Simple.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" Fill_parent " ><imageviewandroid:id= "@+id/img" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:layout_margin= "5DP"/><textviewandroid: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<str         ing, object>> 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 program implements a class table with a picture. First you need to define the XML that good one uses to display the contents of each column.

Vlist.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" Horizontal " > <imageview android:id= "@+id/img" android:layout_width= "Wrap_content" android:layout_height        = "Wrap_content" android:layout_margin= "5px"/> <linearlayout android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:orientation= "vertical" > <textview androi            D:id= "@+id/title" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:textcolor= "#FFFFFFFF" android:textsize= "22px"/> <textview android:id= "@+id/i NFO "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android:tex Tcolor= "#FFFFFFFF" AndroId:textsize= "13px"/> </LinearLayout></LinearLayout> 

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[]{"t            Itle "," 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>> li                st = new Arraylist<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 is composed of generally hashmap corresponding to each row of the ListView. each key-value data for the HASHMAP is mapped to the corresponding ID component in the layout file. Since the system does not have a corresponding layout file available, we can define a layout vlist.xml ourselves. To do the following, the new one simpleadapter parameter is: this, the layout file (vlist.xml), HashMap title and info,img. The component of the layout file is id,title,info,img. Each component of the layout file is mapped to each element of the HashMap, and the adaptation is done.

Operating effects such as:

3) Simplecursoradapter

public class Simplecursoradapteractivity extends Listactivity {     @Override public     void OnCreate (Bundle Savedinstancestate) {         super.oncreate (savedinstancestate);         Get a Cursor object pointing to the system Address Book database to get 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 a database as the data source for Simplecursoradapter .One particular thing to note here: 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 only used for display purposes, we can also add buttons to it. Add a button first to write an XML file with a button, 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 show the button can not add the response of the button, then you need to study how the ListView is realistic, and you must rewrite a class to inherit baseadapter. The following example displays a button and a picture with two lines of words if the button is clicked, the row of the button will be deleted. And tell you exactly how the ListView works.

Vlist2.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" Horizontal " > <imageview android:id= "@+id/img" android:layout_width= "Wrap_content" android:layout_height        = "Wrap_content" android:layout_margin= "5px"/> <linearlayout android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:orientation= "vertical" > <textview androi            D:id= "@+id/title" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:textcolor= "#FFFFFFFF" android:textsize= "22px"/> <textview android:id= "@+id/i NFO "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Android:tex Tcolor= "#FFFFFFFF" AndroId:textsize= "13px"/> </LinearLayout> <button android:id= "@+id/view_btn" Android:layout_wi Dth= "Wrap_content" android:layout_height= "wrap_content" android:layout_gravity= "Bottom|right" Android : text= "@string/s_view_btn"/></linearlayout>
 
 public class MyListView4 extends Listactivity {private list<map<string, object>> 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 arraylist<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 of a selected item in the ListView protected void Onlistitemclick (ListView L, View v, int positio       n, long id) {LOG.V ("Mylistview4-click", (String) mdata.get (position). Get ("title")); /** * Click the button popup dialog box in the listview * * * public void Showinfo () {New Alertdialog.builder (t His). Settitle ("My ListView"). Setmessage ("Introduction ..."). Setpositivebutton ("OK", new Dialoginterfa Ce.               Onclicklistener () {@Override public void 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 (Context context) {This.minflater = Layoutinflater.from (context); } @Override public int getcount () {//TODO auto-generated method stub ret           Urn Mdata.size ();               } @Override public Object getItem (int arg0) {//TODO auto-generated method 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 = 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 (position). Get ("info"));                   Holder.viewBtn.setOnClickListener (New View.onclicklistener () {@Override public void OnClick (VIew v) {showinfo ();                                             }               });           return convertview; }                  }       }


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

When the system displays the list, first instantiate 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 indicates that the first line will be displayed, Covertview is the layout inflate from the layout file. We use the Layoutinflater method to extract the well-defined Vlist2.xml file into a view instance for display. The individual components in the XML file are then instantiated (the Simple Findviewbyid () method). This allows the data to be mapped to individual components. However, in order to respond to a click event, the button needs to be added a click Listener to capture the click event. Now that a custom ListView has been completed, let's go back and look at the process from a new perspective. System to draw the ListView, he first obtains the length of the list to be drawn, and then begins to draw the first line, how to draw it? Call the GetView () function. In this function, we first get a view (actually a viewgroup) and then instantiate and set up each component to show it. Well, finish drawing this line. Then draw the next line until the painting is finished. During the actual run, you will find that each row in the ListView has no focus, because the button robs the ListView of the focus, as long as the button is set to no focus in the layout file.

The effect is as follows:

Reference:

Http://www.cnblogs.com/devinzhang/archive/2012/01/20/2328334.html

       
       

"Side doing project learning Android" Knowledge Point: Adapter Adapter

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.