今回はボタン付などのカスタムしたセルでListViewを作成する方法を記載します。

現在では、リスト表示する場合にはRecyclerViewが基本になっているようですが、ListViewの方が簡単に実装ができるのでレガシーながらも書いていきます。

完成イメージは以下です。

 

1.activity_main.xmlにListViewを貼り付け

メイン画面にListViewを貼り付けます。

デザインタブのパレット→Leagcy→ListViewをD &DでもOK。


<ListView
    android:id="@+id/mainlist"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

2.カスタムセルのrow.xmlを追加

ListViewの1行ずつとなるカスタムセルのレイアウトファイルを以下のように定義します。


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:layout_weight="1"
        android:text="Text1"
        android:textSize="18dp" />

    <TextView
        android:id="@android:id/text2"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="Text2"
        android:gravity="center_vertical|right"
        android:textSize="18dp" />

    <Button
        android:id="@+id/rowbutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:text="BTN" />

</LinearLayout>

3.カスタムセルをListViewにバインドするためのアダプタクラスを作成

バインドするためには、SimpleAdapterクラスがSDKに用意されており、それを継承したListViewAdapterクラスを作成します。


public class ListViewAdapter extends SimpleAdapter {

    private LayoutInflater inflater;
    private List<? extends Map<String, ?>> listData;

    // 各行が保持するデータ保持クラス
    public class ViewHolder {
        TextView text1;
        TextView text2;
    }

    public ListViewAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
        super(context, data, resource, from, to);
        this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        this.listData = data;
    }
}

4.SimpleViewAdapterのgetViewメソッドをOverrideする

row.xmlで用意したTextViewやボタンの実装を行うためにListViewAdapterの中でgetViewメソッドをOverrideします。アプリ起動時やセル選択時に呼ばれます。


@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    final ViewHolder holder;

    // ビューを受け取る
    View view = convertView;

    if (view == null) {
        // 画面起動時にViewHolderを作成する
        view = inflater.inflate(R.layout.row, parent, false);

        holder = new ViewHolder();
        holder.text1 = (TextView) view.findViewById(android.R.id.text1);
        holder.text2 = (TextView) view.findViewById(android.R.id.text2);

        view.setTag(holder);
    } else {
        // 行選択時などは既に作成されているものを取得する
        holder = (ViewHolder) view.getTag();
    }

    // holderにデータをセットする
    String text1 = ((HashMap<?, ?>) listData.get(position)).get("text1").toString();
    String text2 = ((HashMap<?, ?>) listData.get(position)).get("text2").toString();
    holder.text1.setText(text1);
    holder.text2.setText(text2);

    // セル上にあるボタンの処理
    Button btn = (Button) view.findViewById(R.id.rowbutton);
    btn.setTag(position);
    btn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // 選択したセルの文字を赤色にする
            holder.text1.setTextColor(Color.RED);
        }
    });

    return view;
}

5.メイン画面のクラスでListViewに表示するデータをセットする

上記で作成したListViewAdapterクラスにデータを渡す事で表示されます。


public class MainActivity extends AppCompatActivity {
    public static Map<String, String> data;
    public static List<Map<String, String>> dataList;
    public static ListView listView;
    public static ListViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dataList = new ArrayList<Map<String, String>>();

        // ListViewに表示するためのDATAを作成する
        int MAXDATA = 10;
        for (int i = 0; i < MAXDATA; i++) {
            data = new HashMap<String, String>();
            data.put("text1", "タイトル" + i);
            data.put("text2", "サブ" + i);
            dataList.add(data);
        }

        // アダプターにデータを渡す
        adapter = new ListViewAdapter(
                this,
                dataList,
                R.layout.row,
                new String[] { "text1", "text2" },
                new int[] { android.R.id.text1,
                        android.R.id.text2 });

        // アダプターにDATAをSETする
        listView = (ListView) findViewById(R.id.mainlist);
        listView.setAdapter(adapter);
        listView.setTextFilterEnabled(false);

    }
}

 

以上で、カスタムセルをListViewに表示することができます。

 

また、最近リリースしたパスワード 管理アプリ「パスワードメモ」も無料で公開していますのでぜひ使ってみて下さい。