Android Adapter.

Recommended for you: Get network issues from WhatsUp Gold. Not end users.
Android Adapter
Adapter is used to help fill the middle bridge data, such as through it will be filled to ListView, data GridView, Gallery. and Android provides several Adapter:ArrayAdapter, BaseAdapter, CursorAdapter, HeaderViewListAdapter, ListAdapter, ResourceCursorAdapter, SimpleAdapter, SimpleCursorAdapter, SpinnerAdapter, WrapperListAdapter.
According to different sources of data form can choose different Adapter, such as data from a Arraylist using the BaseAdapter, SimpleAdapter, and the data source to obtain it by querying the database using Cursor

Adapter application summary
First, system structure of Adapter:
A Adapter object plays the role of a bridge. This bridge is connected with a AdapterView and the data it contains. Provides a way to the data item Adapter. Adapter is also responsible for each data in the data set in the item to generate a View. It is an important method:
public abstract View getView (int position,View convertView,ViewGroup parent)
. This method is setListAdapter (adapter) indirectly call. The getView method is to get a View, the view display data in the specified location data, or you can manually create a view or inflate from a XML layout. When the view is inflated, its parent view (such as GridView, ListView etc.) will use the default layout parameters, unless you use inflate (int, android.view.ViewGroup, Boolean) method to specify a root view and prevents attachment to root.
The following are about the common several its sub classes:
ListAdapter interface inheritance in Adapter. ListAdapter is a bridge between ListView and list data. Often the data from a Cursor, but this is not necessary. ListView can display any data, as long as it is a ListAdapter package.
Abstract: BaseAdapter is an implementation of the ListView (both in implementation of the ListAdapter interface) and Spinner (implementation of the Spinner interface) with general base class Adapter.
Class ArrayAdapter: a management such ListView ListAdapter: this ListView is supported by an array. This array can be any object. By default, this class is expected to this: associated resources provided ID with a single TextView. If you want to use a more complex layout, you should use the ID constructor contains domain. The domain ID to be associated with a greater layout resources in TextView. It will be for each object in an array of toString () the fill method. You can add usually object's lists or arrays. Rewrite your object's toString () method to decide which one to write data in list text will be displayed. If you want to use some other different from TextView view to show the array (such as ImageViews), or would like to have some (except toString) outside the return value filled in views data, you must override the getView (int, View, ViewGroup) method to return you want to type View.
Class SimpleAdapter: a static data and simple adapter Views corresponds to the definition in XML. You can put on the specified list data into a Map model ArrayList. Corresponding to each entry in ArrayList to list in a line. Maps contains every line of data. You must specify a XML, the XML definition is used to display a line of view. You must specify a corresponding relationship, this relationship is from the Map keys corresponding to the specified views. To bind data to the views occurs in two stages:
If a simpleAdapter.ViewBinder is available, then SetViewValue (android.view.View, Object, String) to be called. If it returns true, then binding occurred. If it returns false, then the views will be sequentially try:
~Implementation of the Checkable View (such as CheckBox), the expected bound value is boolen
~TextView, The expected bound value is String, and the SetViewText method is called
~ImageView, The expected bound value is a resource of ID or String. And the SetViewImage method is called
If no suitable binding is found, a IllegalStateException is thrown.
The following is an example of SimpleAdapter:
/*--------------------mail.xml---------------------------*/
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/MyListView">
/*--------------------simple_list_item_2.xml---------------------------*/
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:id="@+id/ItemImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
android:id="@+id/ItemTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_x="50px"
android:textSize="15pt">
android:id="@+id/ItemText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_x="50px"
android:layout_y="40px">
android:id="@+id/ItemCheck"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="270px">
/*--------------------TestUIList.java---------------------------*/
public class TestUIList extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView list = (ListView) findViewById(R.id.MyListView);
ArrayList> lstImageItem = new ArrayList>();
String[] str1 = { "row one", "row two", "row three", "row four" };
String[] str2 = { "The first line "," second "," third "," fourth lines" };
for (int i = 0; i <str1.length; i++) {
HashMap map = new HashMap();
map.put("ItemImage", R.drawable.icon);
map.put("ItemTitle", str1[i]);
map.put("ItemText", str2[i]);
lstImageItem.add(map);
}
SimpleAdapter saImageItems = new SimpleAdapter(this,
lstImageItem,
R.layout.simple_list_item_2,
new String[] { "ItemImage", "ItemTitle", "ItemText" },
new int[] { R.id.ItemImage, R.id.ItemTitle, R.id.ItemText });
list.setAdapter(saImageItems);
}
}
If you want to achieve ListView for each row is clicked a response events. The province is the succession of a ListActivity. ListActivity is one such Activity: this Activity to display some of the items list by binding to a array or cursor data source, and when the user selects a item, can expose event handler.
ListActivity has a ListView object. The ListView object can be bound to a different data source, especially an array or a Cursor query results. ListActivity has three kinds of usage, respectively is Binding, Screen Layout and Row Layout. The following only discuss the Screen Layout:
ListActivity has a default layout. The layout is composed of one in the center of the screen, separate, full screen list. However, if you want, you can through the onCreate () call setContentView () method to set up your view layout setting screen layout. To do this, your view must contain a ID as "@android:id/android:list" (or in the code in the list object).
Optionally, when you set the view is empty, you can contain any type of view object to display. The "list" notice must have a ID"android:empty".
Note, finally must call setListAdapter (adapter) method to bind the List data through the Adapter display. The indirect setListAdapter method calls the getView method of Adapter, it is you want to return the view type. But when you click the listView item, according to the ListView getView redraw. Examples can be found in "Android SDK development Daquan" in the "Explorer" example.
Want to realize the event listener, to rewrite the protected void onListItemClick (ListView L, View V, int position, long ID) method.
Want to put in the XML custom a line of view progressive display custom in ListActivity ListView, and in each row dynamic binding data, to write a MyAdapter class, the Adapter inherits from BaseAdapter and its constructor has at least one List parameters to realize the dynamic data binding. There are two important steps:
1)Override the getView method, which is one of the most important step is to use items.get (position) method to get the incoming data. The items is a List, it has been assigned to the List parameter's value. Position is the data on the number of rows in the ListView. Get returns the E type. The List template types.
2)Write a class private class ViewHolder. The inner class only member variables, small View component line are you want to display in the ListView.
In order to dynamic into other kinds of data in Adapter, we need to add a in the constructor (or more) List parameters.
Finally we give own some of the MyAdapter with the ListActivity monitoring examples:
/*--------------------MyHome.java-----------------------*/
package com.li.android.myhome;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
public class MyHome extends ListActivity
{
private List items = null;
protected void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
items = new ArrayList();
String[] titles =
{ "The default theme "," theme ", a" B "theme," Mid Autumn Festival "," Pink Lady "," the mood for love" };
for (int i = 0; i <titles.length; i++)
{
String title = titles[i];
items.add(title);
}
setListAdapter(new MyAdapter(this, items));
}
@Override
protected void onListItemClick(ListView l, View v, int position,
long id)
{
new AlertDialog.Builder(MyHome.this).setItems(
R.array.items_my_dialog, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichcountry)
{
}
})
.show();
}
}
/*--------------------MyAdapter.java-----------------------*/
package com.li.android.myhome;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter
{
private LayoutInflater mInflater;
private Bitmap icom_theme;
private Bitmap icon_selected32;
private List items;
public MyAdapter(Context context, List it)
{
mInflater = LayoutInflater.from(context);
items = it;
icom_theme = BitmapFactory.decodeResource(context.getResources(),
R.drawable.theme);
icon_selected32 = BitmapFactory.decodeResource(context
.getResources(), R.drawable.selected32);
}
public int getCount()
{
return items.size();
}
public Object getItem(int position)
{
return items.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
convertView = mInflater.inflate(R.layout.file_row, null);
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.mTheme = (ImageView) convertView.findViewById(R.id.theme);
holder.mSelected32 = (ImageView) convertView
.findViewById(R.id.selected32);
holder.mTheme.setImageBitmap(icom_theme);
String title = items.get(position);
holder.text.setText(title);
holder.mSelected32.setImageBitmap(icon_selected32);
return convertView;
}
private class ViewHolder
{
TextView text;
ImageView mTheme;
ImageView mSelected32;
}
}
/*--------------------main.xml-----------------------*/
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
/*-------------------- file_row.xml-----------------------*/
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
android:id="@+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_x="50px"
android:textSize="15pt">
android:id="@+id/selected32"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="270px">
/*--------------------string.xml-----------------------*/
Hello World, Imitation Panda
Imitation Panda
Applying a theme
Edit theme
Delete the theme
Android Development -- talk about the Adapter thing
Dapter takes an important role in Android, it is the data and UI (View) is an important link between. In the common View (ListView, GridView) and other places need to use Adapter. Fig. 1 intuitive expression of relationship of Data, Adapter, View three.




Figure 1 Adapter, UI data, the relationship between the three (PS: this chart from Google I/O)



Adapter, Android






Adapter type hierarchy diagram in figure 2:Android

From Figure 2 we can see associated with Adapter in Android interface, all full class hierarchy diagram. We use process can according to their own needs to realize interface or class inheritance of certain. Comparison of commonly used with BaseAdapter, ArrayAdapter, SimpleCursorAdapter etc.

·         The BaseAdapter is an abstract class, inheritance method which needs to realize more, so it has high flexibility,
·         ArrayAdapter supports generic operations, usually need to implement the getView method, special circumstances (combination of data row ID), in order to make the UI event handling convenient point best rewrite getItemId,
·         SimpleCursorAdapter can be applied to a simple plain text font ListView, it required fields and UI Cursor ID correspondence. Such as the need to achieve more complex UI can override the other methods.
Code section two, a successor to the BaseAdapter class

   1: /**
2: * song list adapter
   3:  *
4: * @Version 2010-11-24 05:13:33 this afternoon
   5:  * @author Hal
   6:  */
   7: public class AudioListAdapter extends BaseAdapter {
   8:
   9:     private Context mContext;
  10:
  11:     // Song Collection
  12:     private ArrayList<Audio> mAudios;
  13:
  14:     public AudioListAdapter(Context mContext, ArrayList<Audio> mAudios) {
  15:         this.mContext = mContext;
  16:         this.mAudios = mAudios;
  17:     }
  18:
  19:     @Override
  20:     public int getCount() {
  21:         return mAudios != null ? mAudios.size() : 0;
  22:     }
  23:
  24:     @Override
  25:     public Object getItem(int position) {
  26:         if ((mAudios != null && mAudios.size() > 0) && (position >= 0 && position <mAudios.size())) {
  27:             return mAudios.get(position);
  28:         }
  29:         return null;
  30:     }
  31:
  32:     /**
  33:      * If the object in the data set from the database, this method returns the object in the database in ID
  34:      */
  35:     @Override
  36:     public long getItemId(int position) {
  37:         if ((mAudios != null && mAudios.size() > 0) && (position >= 0 && position <mAudios.size())) {
  38:             return mAudios.get(position).getId();
  39:         }
  40:         return position;
  41:     }
  42:
  43:     @Override
  44:     public View getView(int position, View convertView, ViewGroup parent) {
  45:         //TODO returns a custom View
  46:     }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Newman at December 11, 2013 - 5:32 PM