ListView で SingleChoice モード

ListView で一つしか選択できないような List を作ることができます.

基本的には ListView と同じ.
Adapter の作成時に Single Choice ようのレイアウトを設定するのと
setChoiceMode で ListView.CHOICE_MODE_SINGLEを設定するくらい
すると RadioButton 付きのリストが表示されます.

というわけで,SingleChoiceList をいじってみた

サンプルコード
  1. public class SingleChoiceListViewSample extends Activity {  
  2.   @Override  
  3.   public void onCreate(Bundle savedInstanceState) {  
  4.     super.onCreate(savedInstanceState);  
  5.     setContentView(R.layout.listview_sample);  
  6.     ListView listView = (ListView)findViewById(R.id.ListView);  
  7.   
  8.     // アダプタの作成  
  9.     listView.setAdapter(new ArrayAdapter<String>(  
  10.         this,  
  11.         android.R.layout.simple_list_item_single_choice,  
  12.         SIZES)  
  13.     );    
  14.           
  15.     // 選択の方式の設定  
  16.     listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);  
  17.     
  18.     // 指定したアイテムがチェックされているかを設定  
  19.     listView.setItemChecked(0true);  
  20.       
  21.     // アイテムがクリックされた時に呼び出されるコールバックを登録  
  22.     listView.setOnItemClickListener(new OnItemClickListener() {  
  23.         @Override  
  24.         public void onItemClick(AdapterView<?> parent,  
  25.                 View view, int position, long id) {  
  26.             // クリックされた時の処理  
  27.         }  
  28.     });  
  29.     
  30.     // 現在チェックされているアイテムの position を取得  
  31.     listView.getCheckedItemPosition();  
  32.   }  
  33.     
  34.   // ListView に表示させる文字列  
  35.   private static final String[] SIZES = new String[] {  
  36.       "XS(eXtra Small)""S(Small)""M(Medium)",  
  37.    "L(Large)""XL(eXtra Large)"  
  38.   };  
  39. }  

XMLリソース
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.   android:orientation="vertical"   
  4.   android:layout_width="fill_parent"  
  5.   android:layout_height="fill_parent">  
  6.   <TextView android:layout_width="fill_parent"  
  7.     android:layout_height="wrap_content"   
  8.     android:text="ListSample" />  
  9.   <ListView   
  10.     android:layout_width="fill_parent"  
  11.     android:layout_height="0dip"   
  12.     android:layout_weight="1"  
  13.     android:id="@+id/ListView">  
  14.   </ListView>  
  15. </LinearLayout>  

実行すると...



こんな感じ!


参考サイト
http://developer.android.com/intl/ja/reference/android/widget/ListView.html

0 件のコメント:

コメントを投稿