ListViewへヘッダー、フッターの設置

ListViewへヘッダー、フッターの設置

ListViewで
ヘッダー、フッターをそれぞれ別のレイアウトで用意して
ListView.addHeaderView
でヘッダーを設定

ListView.addHeaderView
でフッターを設定できる

使い道としては、クックパッドみたいに
途中に見出しをつけるコンテンツタイプのアプリ
もしくはAdmobによる広告をいれるなど

まずは、ヘッダーのレイアウトを
レイアウトファイルで定義

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="top">
 
<TextView
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="30dip"
android:gravity="center_horizontal"
android:background="@color/custom"
android:text="Header 部品"/>
 
</LinearLayout>

次に、フッター部分も作成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<LinearLayout xmlns:android="http://scheams.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="bottom">
 
<TextView
android:id="@+id/footer"
android:layout_width="match_parent"
android:layout_height="30dip"
android:layout_gravity="center_horizontal"
android:background="@color/custom"
android:text="footer sample"/>
 
</LinearLayout>

次に、JavaでListViewへ
ヘッダーとフッターを追加する

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
View header = (View)getLayoutInflater().inflate(R.layout.header,null);
View footer = (View)getLayoutInflater().inflate(R.layout.footer,null);
 
ListView list = (ListView)findViewById(R.id.list);
list.addHeaderView(header);
list.addFooterView(footer);
 
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
 
 
//アイテムがクリックされたら呼び出されるコールバックを登録
list.setOnItemClickListener(new OnItemClickListener(){
 
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
 
//headerのときは何もしない
if(position ==0){
 
rerun;}
}
});
 
//Adapter作成
list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, LINUX));
 
//フォーカスが当たらないように設定
list.setItemsCanFocus(false)
 
 
//ListViewに表示する文字列
private static final String[] LINUX = new String[]{
"Ubuntu","Fedora","CentOS","OpenSUSE",
};

このように、ヘッダーとフッターのレイアウトファイルを
layoutInflater()で生成して
設定したいListViewへ追加する

注意点としては
ListViewへの追加はできるけど
GridViewへの追加はできない

また、追加されたヘッダーやフッターは
他のアイテムと同様に扱われるため
アイテムの位置が
0番目はヘッダーになり
フッターはn番目とかる

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です