易采站长站为您分析Android App中使用ListFragment的实例教程,ListFragment的内容是以列表(list)的形式显示的Fragment,需要的朋友可以参考下
ListFragment继承于Fragment。因此它具有Fragment的特性,能够作为activity中的一部分,目的也是为了使页面设计更加灵活。
相比Fragment,ListFragment的内容是以列表(list)的形式显示的。ListFragment的布局默认包含一个ListView。因此,在ListFragment对应的布局文件中,必须指定一个 android:id 为 “@android:id/list” 的ListView控件!
ListFragment基础使用
下面介绍在Activity中显示ListFragment的步骤。
1. Activity对应的代码
public class FragmentTest extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
2. Activity对应的布局
<LinearLayout xmlns:android="http://www.easck.com/apk/res/android" xmlns:tools="http://www.easck.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" > <fragment android:name="com.skw.fragmenttest.MyListFragment" android:id="@+id/myfragment" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
说明:该Activity的布局中只包行了一个Fragment。下面看看MyListFragment的内容。
3. MyListFragment的内容
public class MyListFragment extends ListFragment {
private static final String TAG = "##MyListFragment##";
private ListView selfList;
String[] cities = {
"Shenzhen",
"Beijing",
"Shanghai",
"Guangzhou",
"Wuhan",
"Tianjing",
"Changsha",
"Xi'an",
"Chongqing",
"Guilin",
};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView");
return inflater.inflate(R.layout.list_fragment, container, false);
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
// 设置ListFragment默认的ListView,即@id/android:list
this.setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, cities));
}
public void onListItemClick(ListView parent, View v,
int position, long id) {
Log.d(TAG, "onListItemClick");
Toast.makeText(getActivity(), "You have selected " + cities[position],
Toast.LENGTH_SHORT).show();
}
}










