Recyclerview数据集更新正确的方法

时间:2017-05-05 04:48:35

标签: android memory android-recyclerview

更新recyclerview的数据我试过三种方法

  1. notifydatasetchanged()
  2. swapadapter()
  3. 更新List<>并指定相同的适配器。
  4. 但是当我更新每种方法中的数据内存分配(对应用)保持增加的范围(0.25到0.50)MB如何解决?

    我的适配器

    public class RVAdapter extends RecyclerView.Adapter<RVAdapter.PersonViewHolder> {
    public static int Sub;
    
    public static class PersonViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    
    
        TextView personName;
        ImageView personPhoto;
    
        PersonViewHolder(View itemView) {
            super(itemView);
            itemView.setOnClickListener(this);
            personName = (TextView)itemView.findViewById(R.id.person_name);
            personPhoto = (ImageView)itemView.findViewById(R.id.person_photo);
        }
    
        @Override
        public void onClick(View view) {
            Sub = getLayoutPosition();
            Toast.makeText(view.getContext(), "position = " + getLayoutPosition(), Toast.LENGTH_SHORT).show();
    
        }}
    
    List<Person> persons;
    RVAdapter(List<Person> persons){
        this.persons = persons;
    }
    
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }
    
    @Override
    public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.raw, viewGroup, false);
        PersonViewHolder pvh = new PersonViewHolder(v);
        return pvh;
    }
    
    @Override
    public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
        personViewHolder.personName.setText(persons.get(i).name);
        personViewHolder.personPhoto.setImageResource(persons.get(i).photoId);
    }
    
    @Override
    public int getItemCount() {
        return persons.size();
    }
    public void swap(List<Person>persons){
        persons.clear();
        persons.add(new Person("htfg", R.mipmap.ic_launcher));//0
        persons.add(new Person("fhe", R.mipmap.ic_launcher));//0
    notifyDataSetChanged();
    

    } }

1 个答案:

答案 0 :(得分:0)

使用adapter.notifyItemChanged (itemPosition)或任何其他.notifyItem ...()原生适配器方法。