本人新手,最近在学习 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;
}
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.
Search for viewholder yourself. This is listview reusing cells in order to save memory. Just save it with viewholder
This implementation method is not good, let’s use ViewHolder for caching processing. Android data adapter (Adapter) optimization: use efficient ViewHolder
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.
This situation should have nothing to do with ViewHolder
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