Android Adapter usage summary, androidadapter

Source: Internet
Author: User

Android Adapter usage Summary (to), androidadapter

Android Adapter usage Summary

1. Concept

Adapter is an Adapter interface connecting back-end data and front-end display. It is 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 the adapters in Android (Ctrl + T ):

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. Application Cases

1)ArrayAdapter

The display of the list requires three elements:

A. ListVeiw is used to display the View of the list.

B. the adapter is used to map data to the mediation on the ListView.

C. The specific string, image, or basic component of the data to be mapped.

Case 1

Public class ArrayAdapterActivity extends ListActivity {@ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // String [] strs = {"1", "2", "3", "4", "5"} of the list item "}; arrayAdapter <String> adapter = new ArrayAdapter <String> (this, android. r. layout. simple_expandable_list_item_1, strs); setListAdapter (adapter );}}

Case 2

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 data, to assemble the data, you need an Adapter that connects the List View object and the 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)SimpleAdapter
SimpleAdapter 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.

Case 1

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 <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 2
  The following program implements a class table with images. First, you must define an xml, vlist. xml, used to display the content 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;        }    }

 

 

The data using Impleader is generally a List composed of Hash maps. Each section of the list corresponds to each row of Listie. Each key-value data of Hash Map is mapped to the corresponding id component in the layout file. Because the system does not have a corresponding layout file available, we can define a layout alist. XML. The following is an adaptation. The new Impleader parameter is: this, layout file (alist. XML), Hash Map title, info, and IgM. The component id, title, info, and IgM of the layout file. The components of the layout file are mapped to the elements of the Hash Map to complete adaptation.

The running effect is as follows:

 

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: Do not 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, we can also add a button 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.

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 @ Override011 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); 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", "google 3"); 036 map. put ("img", R. drawable. i3); 037 list. add (map); 038 039 return list; 040} 041 042 // logic 043 @ Override044 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 in the listview pop-up dialog box 051 */052 public void showInfo () {053 new AlertDialog. builder (this) 054. setTitle ("My listview") 055. setMessage ("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 large amount of data to load, it will occupy a large amount of memory, affecting performance, in this case, you need to fill in as needed and re-use view to reduce the number of objects to be created. * The fastest way is to define a Pewholder and set the tag of convex to Pewholder, if it is not empty, use the following code again: 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 @ Override084 public int getCount () {085 // TODO Auto-generated method stub086 return mData. size (); 087} 088 089 @ Override090 public Object getItem (int arg0) {091 // TODO Auto-generated method stub092 return null; 093} 094 095 @ Override096 public long getItemId (int arg0) {097 // TODO Auto-generated method stub098 return 0; 099} 100 101 @ Override102 public View getView (int position, view convertView, ViewGroup parent) {103 104 ViewHolder holder = null; 105 if (convertView = null) {106 107 holder = new ViewHolder (); 108 109 convertView = mInflater. inflate (R. layout. vlist2, null); 110 holder. img = (ImageView) convertView. findViewById (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); 114 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 (position ). get ("info"); 125 126 holder. viewBtn. setOnClickListener (new View. onClickListener () {127 128 @ Override129 public void onClick (View v) {130 showInfo (); 131} 132}); 133 134 135 return convertView; 136} 137 138} 139}

 

 

 

  

The code above will be explained in detail below. When listView starts to be drawn, the system first calls the getCount () function to obtain the length of the listView based on its return value, and then according to the length, call getView () to draw each row one by one. 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.

The effect is as follows:

 

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.