ListFragment 内で表示する View をカスタマイズするには、
onCreateView() 内で、差し替えたい View をインフレートします。
以下では、ListFragment のビューを差し替えるために、ListFragment を継承した CustomListFragment クラスを作成し、
オーバーライドした onCreateView() 内で、自作のカスタムビューのリソース(R.layout.custom_listfragment)をインフレートしています。
リソースは、ListFragment の説明ページのもの(緑背景)に対して、幅を 250dp に変更したものを xml に記述しました。
ソースコード
package com.adakoda.android.sample.customlistfragmentsample;
import android.app.Activity;
import android.app.ListFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class CustomListFragmentSampleActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (getFragmentManager().findFragmentById(android.R.id.content) == null) {
CustomListFragment fragment = new CustomListFragment();
getFragmentManager().beginTransaction().add(android.R.id.content,
fragment).commit();
}
}
public static class CustomListFragment extends ListFragment {
public static final String[] ITEMS = { "1", "2", "3", "4", "5", "6",
"7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17",
"18", "20" };
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// 1. 画面幅いっぱいにレイアウトされる
// View view = inflater.inflate(R.layout.custom_listfragment, null);
// 2. クラッシュする
// View view = inflater.inflate(R.layout.custom_listfragment, container);
// 3. 期待した幅でレイアウトされる(正解)
View view = inflater.inflate(R.layout.custom_listfragment, container, false);
// 4. クラッシュする
// View view = inflater.inflate(R.layout.custom_listfragment, container, true);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, ITEMS));
}
}
}
リソース(res\layout\custom_listfragment.xml)
<?xml version="1.0" encoding="utf-8"?>
<!-- View の幅を250dpに変更しています(通常はmatch_parent)-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="250dp"
android:layout_height="match_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<!-- ListView用(idは定義済みのandroid:list)-->
<ListView android:id="@id/android:list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false" />
<!-- アイテムが空の場合に使用するテキスト(idは定義済みのandroid:empty)-->
<TextView android:id="@id/android:empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="No data" />
</LinearLayout>
結果

※画面が小さくてわかりにくいですが、ListView アイテムの背景が緑、幅が250dpになっています
※追記:android:empty だと setEmptyText() で IllegalStateException が発生します。。。(正しい id は?)
※追記2:続きはこちら・・・「Y.A.M の 雑記帳: Android ListFragment でカスタムレイアウトを使うと setEmptyText() が使えない」