Fragment裡添加ListView不要用ListFragment_Android

來源:互聯網
上載者:User

起始的想法是將Fragment和ViewPager結合起來,

然後突發奇想,在第一個Fragment裡添加了ListView,

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

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

複製代碼 代碼如下:

//構造適配器
   List<Fragment> fragments=new ArrayList<Fragment>();
  fragments.add(new Fragment ());
  fragments.add(new Fragment ());
  fragments.add(new Fragment ());
  FPAdapter adapter = new FPAdapter(getSupportFragmentManager(), fragments);

因為是

List<Fragment>

Fragment1用ListFragment自然會報錯。

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

public class Fragment extends Fragment {    private ListView listView;     public View onCreateView(LayoutInflater inflater, ViewGroup container,                Bundle savedInstanceState) {      // TODO Auto-generated method stub      View view= inflater.inflate(R.layout.layout , container, false);      listView = (ListView)view.findViewById(R.id.lv);      ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),          android.R.layout.simple_list_item_ ,getData());      listView.setAdapter(arrayAdapter);      return view;    }    private List<String> getData(){      List<String> data = new ArrayList<String>();      for(int i = ;i < ;i++) {        data.add(i+"");      }      return data;    }  }

 
其中

android.R.layout.simple_list_item_1

是內建的,不用定義。

這樣ListView便能正常顯示了。

以上就是本文的全部內容,希望大家喜歡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.