如何检查RecyclerView适配器中的每个值?

时间:2017-05-15 14:41:07

标签: java android android-recyclerview recycler-adapter

我有一个自定义的RecyclerView适配器,我从包含9个固定数据点的onCreate方法实例化:

    GridRecyclerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ...

        /* Dummy cell data */
        String[] data = {"", "", "", "", "", "", "", "", ""};

        ...

        /* Init RecyclerView */
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        int numColumns = 3;
        recyclerView.setLayoutManager(new GridLayoutManager(this, numColumns));
        adapter = new GridRecyclerAdapter(this, data, numColumns, player1, player2);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

ClickHolder中的clickListener在单击时将文本设置为“X”。

    class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView cellTextView;

        ViewHolder(View itemView) {
            super(itemView);
            cellTextView = (TextView) itemView.findViewById(R.id.textView);
            itemView.setOnClickListener(v -> {
                /* Set cell TextView to "X" */
                cellTextView.setText("X");
            });
        }
    }

每次点击,我想检查itemViews的某个组合是否具有某个值。例如,如果位置1,2和3的itemViews的TextView等于“X”,则显示AlertDialog。我想我应该能够修改每次单击时在构造函数中传递的String []。

1 个答案:

答案 0 :(得分:2)

  1. setOnClickListener中提取ViewHolder并将其移至Adapter's onBindViewHolder
  2. 以某种形式保持检查的位置(例如整数数组)
  3. 当您在某个X上设置Views时,查看所选位置的更改是否有效以显示您的AlertDialog
  4. public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ViewHolder> {
    
        List<Integer> xPositions = new ArrayList<>();
    
        // ... all the needed stuff.
    
        @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {
            holder.itemView.setOnClickListener(v -> {
                holder.showX();
                xPositions.add(holder.getAdapterPosition());
                checkIfShouldShowAlert();
            });
        }
    
        void checkIfShouldShowAlert() {
            // do your checks on xPositions and show the AlertDialog if needed
        }
    
        public static class ViewHolder extends RecyclerView.ViewHolder {
            TextView cellTextView;
    
            ViewHolder(View itemView) {
                super(itemView);
                cellTextView = (TextView) itemView.findViewById(R.id.textView);
            }
    
            void showX(){
                cellTextView.setText("X");
            }
        }
    }
    

    请记住添加一种机制,以阻止对相同视图的连续点击(否则xPositions数组会增长和增长)。