ResourceCursorAdapterは、レイアウトXMLで定義されたViewをリスト項目として生成する
簡易なAdapterです。
DBの値をカスタマイズされたレイアウトでリスト表示したい場合に便利です。
ResourceCursorAdapterを利用する上でのポイントは下記2つのAPIです。
newView(Context, Cursor, ViewGroup)
bindView(View, Context, Cursor)
通例では、それぞれのAPIで下記の処理を実装します。
newView
- 表示するViewをsuper.newViewで生成・取得
- ViewHolderにView参照をキャッシュ
bindView
- ViewHolder経由で、表示する情報を設定
newViewはViewの生成、bindViewはViewへの情報割当を行います。
下記は、list_itemで指定されたレイアウトをリスト表示する簡単なサンプルです。
class ViewHolder {
private TextView label;
}
class CallLogAdapter extends ResourceCursorAdapter {
public CallLogAdapter() {
super(MyListFragment.this.getActivity(),
R.layout.list_item, null, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = super.newView(context, cursor, parent);
ViewHolder holder = new ViewHolder();
holder.label = (TextView)v.findViewById(R.id.label);
v.setTag(holder);
return v;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder)view.getTag();
holder.label.setText(cursor.getString(3/*number*/));
}
};
layout/list_item.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/label" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/hello" /> </LinearLayout>
以上です。