ListFramgent就是一個包含ListView的Fragment,它可以通過資料來源(數組或遊標)顯示一系列的資訊。ListFragment是非常有用處的,就像RSS,可能左邊顯示一個列表,右邊顯示被選中的列表所對應的內容。
可以通過繼承ListFragment建立一個ListFragment對象。下面將展示如何使用ListFragment。
1. 建立一個工程:ListFragmentExample。
2. main.xml中的代碼。
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" ><fragment android:name="net.manoel.ListFragmentExample.Fragment1" android:id="@+id/fragment1" android:layout_weight="0.5" android:layout_width="0dp" android:layout_height="200dp" /><fragment android:name="net.manoel.ListFragmentExample.Fragment1" android:id="@+id/fragment2" android:layout_weight="0.5" android:layout_width="0dp" android:layout_height="300dp" /></LinearLayout>
3、在re/layout下面,建立一個檔案:fragment1.xml。
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ListView android:id="@id/android:list" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:drawSelectorOnTop="false"/> </LinearLayout>
4、在包路徑下面建立一個類:Fragment1.java。
public class Fragment1 extends ListFragment { String[] presidents = { "Dwight D. Eisenhower", "John F. Kennedy", "Lyndon B. Johnson", "Richard Nixon", "Gerald Ford", "Jimmy Carter", "Ronald Reagan", "George H. W. Bush", "Bill Clinton", "George W. Bush", "Barack Obama" }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment1, container, false); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, presidents)); } public void onListItemClick(ListView parent, View v, int position, long id) { Toast.makeText(getActivity(), "You have selected " + presidents[position], Toast.LENGTH_SHORT).show(); } }
5、按F11在模擬器上調試。會看見有兩個資訊列表。
6、隨便點擊一行,就會有一個訊息彈出。
由於在main.xml中分別設定了兩個ListFragment的android:layout_height屬性,所以這兩個列表的高度不一樣。