ReclyclerView和CardView,onclick方法同时在多个CardView上执行操作

时间:2016-03-25 20:52:17

标签: android android-recyclerview android-cardview

我有一个从ArrayList填充的RecyclerView。输出是CardView布局。 在Cardview中,其他视图中有2个按钮。 它们只需要读取TextView的当前值,默认值为1,然后增加或减少它。 Arraylist包含8个项目。

当我运行应用程序时,UI工作正常。麻烦的是当我尝试修改TextView的值时。 在我正在处理的CardView上正确地增加和减少了该值,但是也在另一个CardView上修改了该值。在第二个CardView中,修改其TextView值,也修改了第一个。

那么,我做错了什么?

这是我的片段:

public class Fragment_rosas extends Fragment {


@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.layout_rosas,container,false);

    RecyclerView recyclerview_rosas;
    RecyclerView.Adapter adaptador_rv_rosas;
    RecyclerView.LayoutManager lm_rosas;

    List rosas = new ArrayList();

    rosas.add(new Tropa(1,R.drawable.minibarbaro, getResources().getString(R.string.barbaro),7,1));

    recyclerview_rosas = (RecyclerView) view.findViewById(R.id.recyclerView_tropasRosas);
    recyclerview_rosas.setHasFixedSize(true);

    lm_rosas = new LinearLayoutManager(getContext());
    recyclerview_rosas.setLayoutManager(lm_rosas);

    adaptador_rv_rosas = new AdaptadorTropa(rosas);
    recyclerview_rosas.setAdapter(adaptador_rv_rosas);

    return view;
}

}

这是我的适配器上的代码部分:

@Override
public void onBindViewHolder(final TropaViewHolder viewHolder, int i) {


    viewHolder.imagen.setImageResource(items.get(i).getImagen());
    viewHolder.nombre.setText(items.get(i).getNombre());
    viewHolder.maxnivel.setText(String.valueOf(items.get(i).getNivelMax()));
    viewHolder.espacioencamp.setText((String.valueOf(items.get(i).getEspacioEnCamp())));


    final String nombre = items.get(i).getNombre();
    final int maxnivel = items.get(i).getNivelMax();


    viewHolder.nivelmas.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String niveltemp = viewHolder.nivel.getText().toString();
            String nivelmaxtemp = viewHolder.maxnivel.getText().toString();

            int nivel = Integer.parseInt(niveltemp);
            int maxxnivel = Integer.parseInt(nivelmaxtemp);
            int nuevonivel = nivel+1   ;

            if (nuevonivel<=maxxnivel) {
                viewHolder.txtv_nivel.setText(String.valueOf(nuevonivel));
            }
        }
    });

我的OnCreateViewHolder(这里没有真正发生):

@Override
public TropaViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext())
            .inflate(R.layout.cardview, viewGroup, false);

    return new TropaViewHolder(v);
}

1 个答案:

答案 0 :(得分:0)

这是解决方案,如上面的评论所述,它解决了两个问题: 1. positiontoValueMap - 保存每个位置的当前值 2. onclicklistener传递给onCreateViewHolder中的ViewHolder

适配器类

public class MyAdapter extends RecyclerView.Adapter {
    private Context context;
    private List<String> dataList;
    private Map<Integer, Integer> positionToValueMap = new HashMap<>();

    public MyAdapter(Context context, List<String> dataList) {
        this.context = context;
        this.dataList = dataList;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.recycler_view_item, null, false);

        return new MyViewHolder(view, new OnRecyclerItemClickListener());
    }


    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        ((MyViewHolder) holder).onRecyclerItemClickListener.updatePosition(position);
        ((MyViewHolder) holder).position.setText("" + position);
        ((MyViewHolder) holder).title.setText(dataList.get(position));

        int valueToDisplay = 1;

        if(positionToValueMap.containsKey(position)) {
            valueToDisplay = positionToValueMap.get(position);
        } else {
            positionToValueMap.put(position, valueToDisplay);
        }

        ((MyViewHolder) holder).valueView.setText("value: " + valueToDisplay);
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }

    private class MyViewHolder extends RecyclerView.ViewHolder {
        private OnRecyclerItemClickListener onRecyclerItemClickListener;
        private TextView position;
        private TextView title;
        private TextView valueView;

        public MyViewHolder(View itemView, OnRecyclerItemClickListener onRecyclerItemClickListener) {
            super(itemView);

            itemView.setOnClickListener(onRecyclerItemClickListener);
            this.onRecyclerItemClickListener = onRecyclerItemClickListener;
            this.position = (TextView) itemView.findViewById(R.id.position);
            this.title = (TextView) itemView.findViewById(R.id.title);
            this.valueView = (TextView) itemView.findViewById(R.id.value_view);
        }
    }


    private class OnRecyclerItemClickListener implements View.OnClickListener {
        private int position = -1;

        public void updatePosition(int position) {
            this.position = position;
        }

        @Override
        public void onClick(View v) {
            int oldValue = positionToValueMap.get(position); // get current value
            oldValue++; // increment
            positionToValueMap.put(position, oldValue); // save current value
            notifyItemChanged(position); // update clicked view so that it picks up the new saved value from the positionToValueMap in onBindViewHolder
        }
    }
}

RecyclerView项目布局          

    <TextView
        android:id="@+id/position"
        android:layout_width="30dp"
        android:layout_height="50dp"
        android:textColor="@android:color/white"
        android:gravity="center"
        android:background="@android:color/holo_green_light"
        android:layout_alignParentLeft="true"/>

    <TextView
        android:id="@+id/title"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:textColor="@android:color/white"
        android:gravity="center"
        android:background="@android:color/holo_green_dark"
        android:layout_toRightOf="@id/position" />

    <TextView
        android:id="@+id/value_view"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:textColor="@android:color/white"
        android:gravity="center"
        android:background="@android:color/holo_green_light"
        android:layout_toRightOf="@id/title"
        android:layout_alignParentRight="true"/>
</RelativeLayout>

活动来测试它

public class MainActivity extends AppCompatActivity {
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        recyclerView.setAdapter(new MyAdapter(getApplicationContext(), getSampleData()));
    }

    private static List<String> getSampleData() {
        List<String> dataList = new ArrayList<>();
        dataList.add("zero");
        dataList.add("one");
        dataList.add("two");
        dataList.add("three");
        dataList.add("four");
        dataList.add("five");
        dataList.add("six");
        dataList.add("seven");
        dataList.add("eight");
        dataList.add("nine");
        dataList.add("ten");
        dataList.add("eleven");
        dataList.add("twelve");
        dataList.add("thirteen");
        dataList.add("fourteen");
        dataList.add("fifteen");
        dataList.add("sixteen");
        dataList.add("seventeen");
        dataList.add("eighteen");
        dataList.add("nineteen");
        dataList.add("twenty");

        return dataList;
    }
}

活动布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"/>

</RelativeLayout>