zoukankan      html  css  js  c++  java
  • 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便能正常显示了。

  • 相关阅读:
    每天都感觉很疲劳
    如果你决定要自己营销
    昨天忘记写日记了,今天补充一下!
    终于不用再去北仑了
    良好的程序架构
    最近的天气反复无常
    就这么着
    C# Socket 入门3 UPD
    让程序只启动一次 Mutex
    C# Socket 入门2
  • 原文地址:https://www.cnblogs.com/likeju/p/4700630.html
Copyright © 2011-2022 走看看