我有一个自定义的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 []。
答案 0 :(得分:2)
setOnClickListener
中提取ViewHolder
并将其移至Adapter's
onBindViewHolder
。X
上设置Views
时,查看所选位置的更改是否有效以显示您的AlertDialog
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
数组会增长和增长)。