search

Home  >  Q&A  >  body text

android - ListView 重复显示问题

本人新手,最近在学习 ListView 的应用。我先用 ViewPager + Fragmnet + ActionBar 实现了三个滑动界面。然后在第一个 Fragment 中设置了一个 ListView 用于显示联系人数据。如图一:

接着我滑动到最后一个 Fragment 界面,然后再滑动回来,结果发现 ListView 中的数据重复显示了一遍。如图二:

之后只要滑到最后一个 Fragment 再滑回来一次,ListView 中的联系人列表就会多重复一次。这是什么问题?望高手解答。

贴上自定义 Adapter 的 getView 方法:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
linearLayout = (LinearLayout) inflater.inflate(R.layout.list_contacts, null);
name = (TextView) linearLayout.findViewById(R.id.name_view);
number = (TextView) linearLayout.findViewById(R.id.number_view);
quickContactBadge = (QuickContactBadge) linearLayout.findViewById(R.id.quick_contact_badge);
name.setText(list.get(position).getName());
number.setText(list.get(position).getNumber());
quickContactBadge.assignContactUri(list.get(position).getDetailUri());
quickContactBadge.setImageBitmap(loadPhoto(list.get(position).getPhotoUri()));
return linearLayout;
}

黄舟黄舟2834 days ago924

reply all(5)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 13:45:41

    It may be that the viewpager recycles a fragment. When you slide back and re-instantiate the fragment, you added it repeatedly while the list was still there. Set the viewpager's setOffscreenPageLimit to prevent it from recycling the first one or clear the list when the fragment is recycled.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 13:45:41

    Search for viewholder yourself. This is listview reusing cells in order to save memory. Just save it with viewholder

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:45:41

    This implementation method is not good, let’s use ViewHolder for caching processing. Android data adapter (Adapter) optimization: use efficient ViewHolder

    reply
    0
  • PHPz

    PHPz2017-04-17 13:45:41

    Everyone answered ViewHolder, but unfortunately it does not solve the problem, it just improves efficiency and saves memory.
    The author should post the data loading code.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:45:41

    This situation should have nothing to do with ViewHolder

    • As mentioned above, the getView() method is best to use the Cell reuse mechanism of ListView
    • Repeated display of data should be caused by repeated addition of data in the data source. You will know by printing the contents of the data source ArrayList of ListView
    • There is also the content of ViewPager. It is recommended to study ListView before studying ViewPager, and make good use of Du Niang and the official Demo, Doc

    • Finally: When posting code, use "< >" on the editor toolbar, which is more convenient for others to read

    reply
    0
  • Cancelreply