ListFramgent就是一个包含ListView的Fragment,它可以通过数据源(数组或游标)显示一系列的信息。ListFragment是非常有用处的,就像RSS,可能左边显示一个列表,右边显示被选中的列表所对应的内容。可以通过继承ListFragment创建一个ListFragment对象。

下面将展示如何使用ListFragment。


首先新建一个fragment2.xml

 
  
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  3.     android:layout_width="match_parent" 
  4.     android:layout_height="match_parent" 
  5.     android:orientation="vertical" > 
  6.  
  7.     <ListView 
  8.         android:id="@id/android:list" 
  9.         android:layout_width="match_parent" 
  10.         android:layout_height="match_parent" 
  11.         android:drawSelectorOnTop="false" > 
  12.     </ListView> 
  13.  
  14. </LinearLayout> 

然后我们看下主布局中的代码activity_main.xml

 
  
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  3.     android:id="@+id/fragment_container" 
  4.     android:layout_width="match_parent" 
  5.     android:layout_height="match_parent" 
  6.     android:orientation="vertical" > 
  7.  
  8. </LinearLayout> 

接下来编写Fragment2.java的代码

 
  
  1. package com.example.demo.Fragment; 
  2.  
  3. import com.example.demo.R; 
  4.  
  5. import android.os.Bundle; 
  6. import android.support.v4.app.Fragment; 
  7. import android.support.v4.app.ListFragment; 
  8. import android.view.LayoutInflater; 
  9. import android.view.View; 
  10. import android.view.ViewGroup; 
  11. import android.widget.ArrayAdapter; 
  12. import android.widget.ListAdapter; 
  13. import android.widget.ListView; 
  14. import android.widget.Toast; 
  15.  
  16. public class Fragment2 extends ListFragment { 
  17.     @Override 
  18.     public View onCreateView(LayoutInflater inflater, ViewGroup container, 
  19.             Bundle savedInstanceState) { 
  20.         // TODO Auto-generated method stub 
  21.         super.onCreateView(inflater, container, savedInstanceState); 
  22.         return inflater.inflate(R.layout.fragment2, container, false); 
  23.     } 
  24.  
  25.     String s[]={"1","2","3"}; 
  26.     @Override 
  27.     public void onCreate(Bundle savedInstanceState) { 
  28.         // TODO Auto-generated method stub 
  29.         super.onCreate(savedInstanceState);
  30.         setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,s)); 
  31.     } 
  32.      
  33.     @Override 
  34.     public void onListItemClick(ListView l, View v, int position, long id) { 
  35.         // TODO Auto-generated method stub 
  36.         super.onListItemClick(l, v, position, id); 
  37.         Toast.makeText(getActivity(), s[position], Toast.LENGTH_LONG).show(); 
  38.     } 

运行的效果图: