なぜAndroidのListViewにはSectionがないんだ
セクションさえあればとても便利なのに……と思うタイミングは数多く。
どうしてもセクションを作りたいと思って、ExpandListViewを使うことにしました。
もしかしたら、もっと良い方法が有るのかもしれませんが……。
onGroupClickは、何もせずtrueをreturn
簡単です。以下のとおりです。
- ExpandableListViewに、OnGroupClickListenerをセット
- implementするメソッドonGroupClickで、何もせずtrueをreturn
実装例
public class MyActivity extends Activity implements ExpandableListView.OnGroupClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
...
_expandableListView = (ExpandableListView) findViewById(R.id.listview);
_expandableListView.setGroupIndicator(null); // nullにするとグループのセルの左に出る矢印が消えます
_expandableListView.setChildIndicator(null); // 同様、左に表示されるインジケータが消えます
_expandableListView.setOnGroupClickListener(this);
// 引数: context, 1階層目のdata, cellのlayout, mapKey, 挿入先のlayoutID, 2階層目のdata...
SimpleExpandableListAdapter adapter = new SimpleExpandableListAdapter(
this,
genres,
R.layout.item_group_as_section /* セクションとなるレイアウト */,
new String[] {key},
new int[] {android.R.id.text1},
categories,
R.layout.item_expand_child /* タップできるセルとなるレイアウト */,
new String[] {key},
new int[] {android.R.id.text1}
);
listView.setAdapter(adapter);
// すべてのグループをexpandする処理
for (int i = 0; i < genres.size(); i++) {
listView.expandGroup(i);
}
}
/*
* グループ(セクション)をタップすると、ここが実行される
* trueを返すと、そこで終了。falseを返すと、デフォルトの動作(=collapse/expand)になる
*/
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
return true;
}
}
実装例は長くなってしまいましたが、大事なのは上の数行です。簡単だと思います。