在Fragment中使用Listview

来源:互联网 发布:电磁炮 激光炮 知乎 编辑:程序博客网 时间:2024/05/19 02:28

Fragment中使用ListView

刚接触Fragment,然后再用到ListView的时候真的是遇到了各种问题,原来Fragment中使用ListView和在Activity中在细节上有很多不同的地方。下面就是来说说这些需要注意的细节,下次注意就好了。

在Fragment中使用ListView的注意事项

  • 使用ListFragment可实现包含Listiew的Fragment
    在Fragment中使用ListView最好扩展ListFragment,这样在后面的操作也比较方便。
/** * @描述 在Fragment中要使用ListView,必须要用ListFragment * */public class SayFragment extends ListFragment {
  • 在Fragment的布局中必须包含id 为”@id/android:list”的Listview
<ListView    android:id="@id/android:list"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:divider="@drawable/line"    android:footerDividersEnabled="false"    android:headerDividersEnabled="false"/>
  • 只能使用SimpleAdapter或者SimpleCursorAdapter作为适配器

其实这里并不是只能用simpleAdapter,还可以使用BaseAdapter,因为simpleAdapter是继承BaseAdapter的。在大多数情况下啊,比如我做的这个项目中,使用的就是BaseAdapter,因为重写BaseAdapter可以更加灵活的去复杂的item绑定数据。

  • 直接使用ListFragment的setListAdapter()来设置适配器,不要给ListView设置!!在给simpleAdapter设置参数的时候,第一个参数为getActivity()
simpleAdapter = new SimpleAdapter( getActivity(),listItems,      R.layout.fragment_sport_say_item,      new String[]{"userImage","userName","content"},      new int[]{R.id.user_image,R.id.user_name,R.id.content});setListAdapter(simpleAdapter);

大概要注意的就是这些了,然后例子后面再写吧,后面会写一篇关于实现朋友圈功能的文章,我用的就是在Fragment使用ListView,关于朋友圈的功能网上真的是很多demo,可是觉得功能都不是很完善,我在项目中实现了,发布,点赞还有评论的功能,但是还有的地方需要完善,所以这个文章等以后整理好了再写吧。

0 1
原创粉丝点击