参考《Professional Android 4 Development》
Adapters简介
Adapter用于将数据和实现AdapterView接口的ViewGroup绑定在一起。Android SDK内置了很多Adapter,比较常用的有这两个:
- ArrayAdapter:将Array和一个Adapter View绑定到一起,默认调用Array中对象的toString方法并将String其填充到Text View中。
- SimpleCursorAdapter:将Adapter View和Cursor中的列绑定到一起。
自定义ArrayAdapter
ArrayAdapter的默认功能是调用Array中对象的toString()方法,然后这些String将显示在TextView中。显然,我们可以将这个模式推广到更多的应用场景中,方法就是使用自定义ArrayAdapter。
自定义ArrayAdapter最常用的方法是重写(override)ArrayAdapter中的getView方法,如:
public class MyArrayAdapter extends ArrayAdapter<MyClass> { int resource; public MyArrayAdapter(Context context, int _resource, List<MyClass> items) { super(context, _resource, items); resource = _resource; } @Override public View getViewew (int position, View convertView, ViewGroup parent) { // Create and inflate the View to display LinearLayout newView; if (convertView == null) { // Inflate a new view if this is not an update. newView = new LinearLayout(getContext()); String inflater = Context.LAYOUT_INFLATER_SERVICE; LayoutInflater li; li = (LayoutInflater)getContext().getSystemService(inflater); li.inflate(resource, newView, true); } else { // Otherwise we’ll update the existing View newView = (LinearLayout)convertView; } MyClass classInstance = getItem(position); // TODO Retrieve values to display from the classInstance variable. // TODO Get references to the Views to populate from the layout. // TODO Populate the Views with object property values. return newView; }
getView的参数分别是要显示的item在数组中的位置,即将更新的View,以及这个View所在的ViewGroup。
使用Adapter将Data和View绑到一起
ArrayList<String> myStringArray = new ArrayList<String>(); int layoutID = android.R.layout.simple_list_item_1; ArrayAdapter<String> myAdapterInstance; myAdapterInstance = new ArrayAdapter<String>(this, layoutID, myStringArray); myListView.setAdapter(myAdapterInstance);
上面的例子将String和TextView绑到一起,是ArrayAdapter中最简单的情形。
Simple Cursor Adapter
LoaderManager.LoaderCallbacks<Cursor> loaded = new LoaderManager.LoaderCallbacks<Cu rsor>() { public Loader<Cursor> onCreateLoader(int id, Bundle args) { CursorLoader loader = new CursorLoader(MyActivity.this, CallLog.CONTENT_URI, null, null, null, null); return loader; } public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { String[] fromColumns = new String[] {CallLog.Calls.CACHED_NAME, CallLog.Calls.NUMBER}; int[] toLayoutIDs = new int[] { R.id.nameTextView, R.id.numberTextView}; SimpleCursorAdapter myAdapter; myAdapter = new SimpleCursorAdapter(MyActivity.this, R.layout.mysimplecursorlayout, cursor, fromColumns, toLayoutIDs); myListView.setAdapter(myAdapter); } public void onLoaderReset(Loader<Cursor> loader) {} }; getLoaderManager().initLoader(0, null, loaded);
SimpleCursorAdapter构造函数的参数分别为当前的context,显示cursor中数据的View Layout,Cursor,以及两个同样大小的整型数组:一个包含columns的index,另一个包含resource id。