Fragment中添加ListView而不使用ListFragment


最初的構想是,將Fragment和ViewPager結合起來,

然后突發奇想,在第一個Fragment里添加了ListView,

依照網上的建議,extends了ListFragment,接着各種報錯。

仔細看了下,原來是MainActivity這里:

1 //構造適配器
2  List<Fragment> fragments=new ArrayList<Fragment>();
3 fragments.add(new Fragment1());
4 fragments.add(new Fragment2());
5 fragments.add(new Fragment3());
6 FPAdapter adapter = new FPAdapter(getSupportFragmentManager(), fragments);

因為是

List<Fragment>

Fragment1用ListFragment自然會報錯。

修改Fragment1里代碼,添加ListView的方法如下:

 1 public class Fragment1 extends Fragment {
 2 
 3     private ListView listView;
 4 
 5 
 6     public View onCreateView(LayoutInflater inflater, ViewGroup container,
 7                              Bundle savedInstanceState) {
 8         // TODO Auto-generated method stub
 9         View view= inflater.inflate(R.layout.layout1, container, false);
10         listView = (ListView)view.findViewById(R.id.lv);
11         ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),
12                 android.R.layout.simple_list_item_1,getData());
13         listView.setAdapter(arrayAdapter);
14 
15         return view;
16     }
17 
18     private List<String> getData(){
19         List<String> data = new ArrayList<String>();
20         for(int i = 0;i <20;i++) {
21             data.add(i+"");
22         }
23         return data;
24     }
25 }

其中

android.R.layout.simple_list_item_1

是自帶的,不用定義。

 

這樣ListView便能正常顯示了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM