リストビュー (ListView) のアイテム選択モード

リストビュー (ListView) は、デフォルトではアイテムが選択されないリストビューですが、選択モードの設定を変更することで 1 つもしくは複数のアイテムを選択できるリストビューにすることができます。


リストビューのアイテムを選択できるようにするには、ListView の choiceMode を設定します。

ここでは、アイテムを選択できるリストビューの作成方法と、ボタンクリック時に選択したアイテムを取得・表示する例を説明します。

リソース (xml) の定義

リソースの定義には、ListView を追加します。通常の ListView と異なる点は、choiceMode 属性を設定するところです。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

  <ListView
    android:id="@+id/listView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:choiceMode="multipleChoice"
  />
  <Button
    android:id="@+id/btnOk"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="OK"/>

</LinearLayout>

※ 「OK」の文字列は、本来 string.xml に定義すべきですが、説明を簡単にするために直接記述しています。

ソースコードの定義

ソースコードでは、

  1. リストビュー (ListView) に設定するアイテムの生成
  2. アイテムをリストビュー (ListView) に設定
  3. ボタンクリックイベント内で、選択アイテムを取得

という処理をします。

package jp.sample.listview;

import android.app.Activity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class ListViewSampleActivity extends Activity {

    // リストに設定するアイテム
    private final String[] item = new String [] {
        "listView item 1",
        "listView item 2",
        "listView item 3"
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // 追加するアイテムを生成する
          ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                  this, android.R.layout.simple_list_item_multiple_choice, item);

        // リストビューにアイテム (adapter) を追加
        ListView listView1 = (ListView)findViewById(R.id.listView1);
        listView1.setAdapter(adapter);

        // ボタンクリックイベント
        Button btn = (Button)findViewById(R.id.btnOk);
        btn.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // 選択アイテムを取得
                ListView listView1 = (ListView)findViewById(R.id.listView1);
                SparseBooleanArray checked = listView1.getCheckedItemPositions();

                // チェックされたアイテムの文字列を生成
                // checked には、「チェックされているアイテム」ではなく、
                // 「一度でもチェックされたアイテム」が入ってくる。
                // なので、現在チェックされているかどうかを valutAt の戻り値
                // で判定する必要がある!!!
                StringBuilder sb = new StringBuilder();
                for (int i=0; i<checked.size(); i++) {
                    if (checked.valueAt(i)) {
                        sb.append(item[i]+",");
                    }
                }
                // 通知
                Toast.makeText(ListViewSampleActivity.this,
                               sb.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

※ 「OK」の文字列は、本来 string.xml に定義すべきですが、説明を簡単にするために直接記述しています。

説明

ポイントとなるところを説明していきます。

リソースの定義

リソースの定義では、ListView に choiceMode を設定することで、アイテムを選択できるリストビューにします。

<ListView
  android:id="@+id/listView1"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:choiceMode="multipleChoice"
/>

singleChoice を設定すると、1 つのアイテムを選択するモード
multipleChoice を設定すると、複数のアイテムを選択するモード
になります。

ListView に設定するアイテムの生成

ListView に設定するアイテムはここでは文字列だけなので、通常のリストビューと同様に ArrayAdapter<String> で設定しています。
但し、第二引数の xxx には、simple_list_item_multiple_choice を設定します。

// 追加するアイテムを生成する
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
        this, android.R.layout.simple_list_item_multiple_choice, item);

1 つのアイテムを選択するモードの場合は、
simple_list_item_single_choice
を設定します。

ListView で選択されているアイテムの取得

ListView で選択されているアイテムを取得するには、getCheckedItemPositions メソッドを使用します。
但し、このメソッドの戻り値 (SparseBooleanArray 型) には一度選択されたアイテムが入ってくるので、SparseBooleanArray の valueAt メソッドを使用し、チェック状態 (true/false) を取得し、判断する必要があります。

// 選択アイテムを取得
ListView listView1 = (ListView)findViewById(R.id.listView1);
SparseBooleanArray checked = listView1.getCheckedItemPositions();

for (int i=0; i<checked.size(); i++) {
    if (checked.valueAt(i)) {
        // true の場合、選択されているアイテム
    }
}

リストビュー (ListView) 関連の記事

 ⇒ リストビュー (ListView) の使い方
 ⇒ リストビュー (ListView) のアイテム選択イベント