ExpandListViewで階層表示
ExpandListViewに階層データを保持するAdapterを設定することで
画面に階層表示のリスト表示を作ることができる
モバイルのWikipediaとか
スマホ向けのクックパッドで
押すとリストがでるようなかんじ
大きな見出しと、詳細記事などを作るときに使える
ExpandListViewは
折りたたみ可能なListView
親リストへはカテゴリー
子リストにはデータを配置して
カテゴリーだけ表示するために
データを折りたたんで表示するときに使う
ExpandListViewを使うには
まずレイアウトファイルでExpandListViewを設定
<ExpandListView android:id="@+id/expandlist" android:layout_width="match_parent" android:layout_height="match_parent" />
次に、JavaでAdapterの設定をする
ExpandListViewのインスタンスを取得し
データを設定したAdapterをセットする
//親リスト作成
ArrayList<HashMap<String,String>> groupData = new ArrayList<HashMap<String,String>>();
//子リスト作成
ArrayList<HashMap<String,String>> childData = new ArrayList<ArrayList<HashMap<String,String>>>();
//親リストを要素追加
HashMap<String,String> groupA = new HashMap<String,String>();
groupA.put("group","Linux");
HashMap<String,String> groupB = new HashMap<String,String>();
groupB.put("group","Android");
groupData.add(groupA);
groupData.add(groupB);
//Linuxの子リストへ要素追加
ArrayList<HashMap<String,String>> childListA = new ArrayList<HashMap<String,String>>();
HashMap<String,String> childA = new HashMap<String,String>();
childA.put("group","Linux");
childA.put("name","Ubuntu");
HashMap<String,String> childB = new HashMap<String,String>();
childB.put("group","Linux");
childB.put("name","CentOS");
HashMap<String,String> childC = new HashMap<String,String>();
childC.put("group","Linux");
childC.put("name","Fedora");
childListA.add(childA);
childListA.add(childB);
childListA.add(childC);
//Androidの子リストへ要素追加
ArrayList<HashMap<String,String>> childListB = new ArrayList<HashMap<String,String>>();
HashMap<String,String> childBA = new HashMap<String,String>();
childBA.put("group","Android");
childBA.put("name","Nexus7");
HashMap<String,String> childBB = new HashMap<String,String>();
childBB.put("group","Android");
childBB.put("name","Nexus5");
childListB.add(childBA);
childListB.add(childBB);
childData.add(childListB);
//親リスト、子リストを含んだAdapterを作成
SimpleExpandableListAdapter adapter = new SimpleExpandableListAdapter(
getApplicationContext(),
groupData(),
android.R.layout.simple_expandable_list_item_2,
new String[]{"name","group"},
new int[]{android.R.id.text1,android.R.id.text2}
);
//ExpandableListViewにAdapterをセット
ExpandableListView exList = (ExpandableListView)findViewById(R.id.expandlist);
exList.setAdapter(adapter);
ExpandableListViewのデータ構造は
階層構造になるため
ListView
GridViewのような単一データ構造ではない
なので、Adapterとしては
ExpandableListAdapterクラスを継承したAdapterである必要がある
ExpandableListAdapterクラスは内部で
親データの取得用メソッドと
子データの取得用メソッドがあるので
これをOverrideすることで
複雑な階層構造のデータ形式を扱えるようになる

