Android Adapter Usage Summary-

Source: Internet
Author: User

Adapter Usage Summary of Android

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). Adapter is needed in places such as the common view (List View,grid view). 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 Base adapter,impleader,adapter,counteradaptation 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 Cases

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<string> ();            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 adapter (context context, int resourcefulness, list<t> objects) to assemble the data, and to assemble the data requires a connection List View view objects and array data adapters to fit the work, the adapter construction requires three parameters, followed by this, the layout file (note Here the layout file describes the list of each row of the layout, 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 adapter () 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 (buttons), CheckBox (checkboxes), 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<st         Ring, 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 is to implement a class table with a picture. First you need to define the xml,vlist.xml that good one uses to display the contents of each column

 <?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=" WR Ap_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_cont Ent "android:textcolor=" #FFFFFFFF "android:textsize=" 13px "/> </LinearLayout> </line Arlayout> 
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>> l                 ist = 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 Impleader data, which is usually a hash map, corresponds to each row of the Listie. Each key value data for the Hash map 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 alist ourselves. Xml. The following is the adaptation, the new one impleader parameter is: this, the layout file (alist. XML), the title and Info,igm of the Hash map. The component of the layout file is Id,title,info,igm. Each component of the layout file is mapped to each element of the hash map, and is adapted to fit.

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 a data source, before using Simplecursoradapter, it is particularly important to note that: Do not forget to add permissions in 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:orientation=" horizontal "android:layout_width=" Fill_parent "android:layout_height=" Fill_parent "&        Gt <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=" Wra            P_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> <button Android Oid:id= "@+id/view_btn" Android:layout_widtH= "Wrap_content" android:layout_height= "wrap_content" android:text= "@string/s_view_btn" android:layout_gravity = "Bottom|right"/> </LinearLayout>

/**002 * @author 003 *004 */005 public class MyListView4 extends Listactivity {006 007 008 P Rivate list<map<string, object>> mdata;009 010 @Override011 public void OnCreate (Bundle savedinstancestate) {012 super.oncreate (savedinstancestate); 013 Mdata = GetData (); 014 MyA Dapter adapter = new Myadapter (this); 015 Setlistadapter (adapter); 016}017 018 Private LIST&LT ; Map<string, object>> GetData () {019 list<map<string, object>> List = new arraylist<map& Lt            String, Object>> (); 020 021 map<string, object> Map = new hashmap<string, object> (); 022 Map.put ("title", "G1"), 023 map.put ("info", "Google 1"), 024 map.put ("img", R.DRAWABLE.I1); 02 5 List.add (map); 026 027 map = new hashmap<string, object> (); 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<string, object> (), 034 map.put ("title", "G3"), 035 map.put ("info", "Goog Le 3 "); 036 map.put (" img ", R.DRAWABLE.I3); 037 List.add (map); 038 039 return lis t;040}041 042//The logical 043 of a selected item in the ListView @Override044 protected void Onlistitemclick (L Istview L, View v, int position, long id) {045 046 log.v ("Mylistview4-click", (String) Mdata.get (pos  ition). Get ("title")); 047}048 049/**050 * ListView Click the button Pop-up dialog 051 */052 public void Showinfo () {053 new Alertdialog.builder (This) 054. Settitle ("My ListView") 055. setmess                 Age ("Introduction ...") 056. Setpositivebutton ("OK", new Dialoginterface.onclicklistener () {057 @Override058 Public VOID OnClick (dialoginterface dialog, int which) {059}060}) 061. Show (); 062          063}064/**  When Listie has a lot of data to load, it takes up a lot of memory and affects performance, when     needs to populate and re-use view to reduce the creation of objects by 065 * The quickest way is to define a pewholder, to set the convex tag to pewholder, and not to use it again when it is empty 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 CLA SS Myadapter extends baseadapter{076 077 private layoutinflater minflater;078 079 0            Myadapter Public (context context) {081 This.minflater = layoutinflater.from (context); 082 }083 @Override084 public int getcount () {085//TODO auto-generated method stub 086 return mdata.size (); 087}088 089 @Override090 public Object getite m (int arg0) {091//TODO auto-generated method stub092 return null;093}094 0 @Override096 public long Getitemid (int arg0) {097//TODO auto-generated Method St ub098 retUrn 0;099}100 101 @Override102 public View getView (int position, view Convertview, V Iewgroup parent) {103 104 Viewholder holder = null;105 if (Convertview = = Nu                    LL) {106 107 holder=new Viewholder (); 108 109 Convertview = minflater.inflate (r.layout.vlist2, null); holder.img = (ImageView) convertview.findvi                    Ewbyid (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); 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 (PO sition). Get ("info")), 126 Holder.viewBtn.setOnClickListener (new View.onclicklistener () {                        127 @Override129 public void OnClick (View v) {130                Showinfo (); 131}132}); 133 134 135 Return Convertvie w;136}137 138} 139}

  

The following will be a detailed explanation of the above code, the ListView at the beginning of the drawing, the system first calls the GetCount () function, according to his return is worth to the length of the ListView, and then according to this length, call GetView () to draw each row. 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:

Transferred from: http://blog.csdn.net/fznpcy/article/details/8658155

Android Adapter Usage Summary-(GO)

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.