ListViewで画像を表示する
ListViewでTextViewとImageView両方扱えるようにSimpleCursorAdapterを拡張してみました。
public class ImageCursorAdapter extends SimpleCursorAdapter { private int mTo[]; public ImageCursorAdapter(Context context, int layout, Cursor c, String from[], int to[]) { super(context, layout, c, from, to); mTo = to; } @Override public void bindView(View view, Context context, Cursor cursor) { for(int i = 0; i < mTo.length; i++) { View v = view.findViewById(mTo[i]); if (v == null) continue; String text = cursor.getString(mFrom[i]); if (text == null) text = ""; if (v instanceof TextView) { setViewText((TextView)v, text); } else if (v instanceof ImageView) { setViewImage((ImageView)v, text); } } } public void setViewImage(ImageView v, CharSequence text) { if (text != "") { v.setImageResource(Integer.parseInt(text.toString())); } } }
DBにはR.drawable.xxの数値を直接登録します。例えば
public final class R { public static final class drawable { public static final int icon=0x7f020000; public static final int message_arrival=0x7f020001; } : }
となっていればiconやmessage_arrivalの値をそのままDBに登録してやります。
使い方はSimpleCursorAdapterと同じです。
Cursor cursor = managedQuery(Hoge.ContentURI, null, null, null); ImageCursorAdapter contacts = new ImageCursorAdapter(this, R.layout.contact, cursor, new String[] { "Hoge1" "Hoge2" }, new int[] { R.id.hoge1, R.id.hoge2 }); setListAdapter(contacts);
レイアウトファイルはこんな感じになります。
<?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"> <TextView id="@+id/hoge1" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <ImageView id="@+id/hoge2" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
改良しだいではでImageView以外も使えるようになるかと思います。