Adapter Usage Summary of Android

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 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 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, and the layout file (note here that the layout file 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"
>
<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: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>> 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,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= "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>
</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[]{"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 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 contacts database to get the data source
Cursor cur = getcontentresolver (). query (People.content_uri, NULL, NULL, NULL, or NULL);
Startmanagingcursor (cur);
Instantiating a 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" >
<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>

<button android: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 Private list<map<string, object>> mdata;
009
010 @Override
011 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<map<string, object>> GetData () {
019 list<map<string, object>> List = new arraylist<map<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);
025 List.add (map);
12W
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", "Google 3");
036 map.put ("img", R.DRAWABLE.I3);
037 List.add (map);
038
039 return list;
040}
041
042//The logic of a selected item in the ListView
043 @Override
044 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 popup dialog box in the ListView
051 */
052 public void Showinfo () {
053 New Alertdialog.builder (this)
054. Settitle ("My ListView")
055. Setmessage ("Introduction ...")
056. Setpositivebutton ("OK", new Dialoginterface.onclicklistener () {
057 @Override
058 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 @Override
084 public int GetCount () {
085//TODO auto-generated method stub
086 return mdata.size ();
087}
088
089 @Override
090 public Object getItem (int arg0) {
091//TODO auto-generated method stub
092 return null;
093}
094
095 @Override
096 public long Getitemid (int arg0) {
097//TODO auto-generated method stub
098 return 0;
099}
100
101 @Override
102 Public View GetView (int position, view Convertview, ViewGroup parent) {
103
104 Viewholder holder = null;
if (Convertview = = null) {
106
107 holder=new Viewholder ();
108
109 Convertview = minflater.inflate (r.layout.vlist2, NULL);
Holder.img = (ImageView) Convertview.findviewbyid (r.id.img);
111 Holder.title = (TextView) Convertview.findviewbyid (r.id.title);
Holder.info = (TextView) Convertview.findviewbyid (r.id.info);
113 holder.viewbtn = (Button) Convertview.findviewbyid (R.ID.VIEW_BTN);
Convertview.settag (holder);
115
}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
@Override
129 public void OnClick (View v) {
Showinfo ();
131}
132});
133
134
135 return Convertview;
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 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:



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

Adapter Usage Summary of Android

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.