2011年10月4日火曜日

Android SimpleCursorAdapter で ViewBinder を使う

SimpleAdapter で ViewBinder を使う方法は Android Layout CookBook に書いたので、SimpleCursorAdapter で ViewBinder を使う方法を紹介します。

SimpleCursorAdapter.ViewBindersetViewValue() メソッドでは第2引数としてその行の Cursor と、第3引数として列の columnIndex が渡されるので、これを使ってそのカラムに表示したいデータを取得して、色を変えたり文字の大きさを変えたり表示するデータを別のテーブルからとってきたりして、対象の View にセットします。

  1. public class SimpleCursorAdapterSampleActivity extends ListActivity {  
  2.   
  3.     private static final String[] PHONE_PROJECTION = new String[] {  
  4.         Phone._ID,  
  5.         Phone.TYPE,  
  6.         Phone.NUMBER  
  7.     };  
  8.   
  9.     private static final int COLUMN_TYPE = 1;  
  10.   
  11.     private static final int[] COLOR_LIST = new int[] {  
  12.         Color.parseColor("#002A42"),  
  13.         Color.parseColor("#3DC3EA"),  
  14.         Color.parseColor("#99417B"),  
  15.         Color.parseColor("#F2AE30"),  
  16.         Color.parseColor("#F2D338"),  
  17.     };  
  18.       
  19.     @Override  
  20.     protected void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.   
  23.         Cursor c = getContentResolver().query(  
  24.                 Phone.CONTENT_URI,  
  25.                 PHONE_PROJECTION,   // projection  
  26.                 null,   // selection  
  27.                 null,   // selectionArgs  
  28.                 null    // orderBy  
  29.                 );  
  30.         startManagingCursor(c);  
  31.   
  32.         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,  
  33.                 android.R.layout.simple_list_item_2,   
  34.                 c,  
  35.                 new String[] { Phone.TYPE, Phone.NUMBER },  
  36.                 new int[] { android.R.id.text1, android.R.id.text2 });  
  37.           
  38.         adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {  
  39.               
  40.             public boolean setViewValue(View view, Cursor cursor, int columnIndex) {  
  41.                 if (columnIndex == COLUMN_TYPE) {  
  42.                     int type = cursor.getInt(COLUMN_TYPE);  
  43.                     String text = (String) Phone.getTypeLabel(getResources(), type, null);  
  44.                       
  45.                     ((TextView) view).setText(text);  
  46.                     ((TextView) view).setTextColor(COLOR_LIST[type % 5]);  
  47.                     return true;  
  48.                 }  
  49.                 return false;  
  50.             }  
  51.         });  
  52.         setListAdapter(adapter);  
  53.     }  
  54. }  



0 件のコメント:

コメントを投稿