Adapters are bridging classes that bind data to Views (such as List Views) used in the user interface.
Some Native Adapters
ArrayAdapter The Array Adapter uses generics to bind an Adapter View to an array of
objects of the specified class.
SimpleCursorAdapter The Simple Cursor Adapter attaches Views specified within a lay-
out to the columns of Cursors returned from Content Provider queries.
Customizing the Array Adapter
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 getView(int position, View convertView, ViewGroup parent) {
LinearLayout newView;
MyClass classInstance = getItem(position);
// TODO Retrieve values to display from the
// classInstance variable.
// Inflate a new view if this is not an update.
if (convertView == null) {
newView = new LinearLayout(getContext());
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater vi = (LayoutInflater)getContext().getSystemService(inflater);
vi.inflate(resource, newView, true);
} else {
newView = (LinearLayout)convertView;
}
// TODO Retrieve the Views to populate
// TODO Populate the Views with object property values.
return newView;
}
}
Using Adapters for DataBinding
ArrayList<String> myStringArray = new ArrayList<String>();
ArrayAdapter<String> myAdapterInstance;
int layoutID = android.R.layout.simple_list_item_1;
myAdapterInstance = new ArrayAdapter<String>(this, layoutID , myStringArray);
myListView.setAdapter(myAdapterInstance);
myAdapterInstance.notifyDataSetChanged();
Using the Simple Cursor Adapter
The SimpleCursorAdapter lets you bind a Cursor to a List View, using a custom layout definition to
define the layout of each row/item, which is populated by a row’s column values.
String uriString = "content://contacts/people/";
Cursor myCursor = managedQuery(Uri.parse(uriString), null, null, null);
String[] fromColumns = new String[] {People.NUMBER, People.NAME};
int[] toLayoutIDs = new int[] { R.id.nameTextView, R.id.numberTextView};
SimpleCursorAdapter myAdapter;
myAdapter = new SimpleCursorAdapter(this,
R.layout.simplecursorlayout,
myCursor,
fromColumns,
toLayoutIDs);
myListView.setAdapter(myAdapter);
本文深入探讨了适配器作为桥梁类在用户界面中的作用,尤其关注如何通过ArrayAdapter和SimpleCursorAdapter实现数据与视图的高效绑定。文章详细介绍了如何自定义ArrayAdapter,并通过实例展示了如何使用适配器进行数据绑定,以及如何利用SimpleCursorAdapter从内容提供者查询中获取数据并展示。
1862

被折叠的 条评论
为什么被折叠?



