LoginSignup
5
5

More than 5 years have passed since last update.

iOSのリストっぽいのを作るために、ExpandableListViewをExpand/Collapseしないようにする

Posted at

なぜAndroidのListViewにはSectionがないんだ

セクションさえあればとても便利なのに……と思うタイミングは数多く。

どうしてもセクションを作りたいと思って、ExpandListViewを使うことにしました。
もしかしたら、もっと良い方法が有るのかもしれませんが……。

onGroupClickは、何もせずtrueをreturn

簡単です。以下のとおりです。

  1. ExpandableListViewに、OnGroupClickListenerをセット
  2. 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;
    }

}

実装例は長くなってしまいましたが、大事なのは上の数行です。簡単だと思います。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5