如何更改 RecyclerView 中的元素
How to change an element of a RecyclerView from one that is inside of it
我有一个 RecyclerView,我想在其中创建如下图所示的内容
简而言之:我想禁用一个选中的复选框被激活,当另一个列表被激活时。
这是我的 RecyclerView 适配器:
@Override
public void onBindViewHolder(final MyHolder holder, final int position) {
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
/*Here I want to disable this on. I need to have a single enabled checkbox.*/
//((CheckBox) holder.itemView.findViewById( )).setChecked(false);
}
});
}
因为我可以禁用 CheckBox 勾选了这个。
对不起我的英语...
这不是最优雅的解决方案,但您可以为整个适配器创建一个名为 currentlyChecked 的 CompoundButton 变量。当触发 onCheckedChange 时,调用
currentlyChecked.setChecked(false);
希望对您有所帮助
在构造方法中添加这个 int 变量:
int currentCheckedPosition = -1 ; // hold checked position
然后在 OnBindView() 中执行此操作:
@Override
public void onBindViewHolder(final MyHolder holder, final int position) {
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
currentCheckedPosition = holder.getAdapterPosition();
holder.checkbox.setChecked(b);
} else {
currentCheckedPosition = - 1 ;
}
notifyDataSetChanged();
}
});
holder.checkBox.setChecked(position == currentCheckedPosition);
}
我有一个 RecyclerView,我想在其中创建如下图所示的内容
简而言之:我想禁用一个选中的复选框被激活,当另一个列表被激活时。
这是我的 RecyclerView 适配器:
@Override
public void onBindViewHolder(final MyHolder holder, final int position) {
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
/*Here I want to disable this on. I need to have a single enabled checkbox.*/
//((CheckBox) holder.itemView.findViewById( )).setChecked(false);
}
});
}
因为我可以禁用 CheckBox 勾选了这个。 对不起我的英语...
这不是最优雅的解决方案,但您可以为整个适配器创建一个名为 currentlyChecked 的 CompoundButton 变量。当触发 onCheckedChange 时,调用
currentlyChecked.setChecked(false);
希望对您有所帮助
在构造方法中添加这个 int 变量:
int currentCheckedPosition = -1 ; // hold checked position
然后在 OnBindView() 中执行此操作:
@Override
public void onBindViewHolder(final MyHolder holder, final int position) {
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
currentCheckedPosition = holder.getAdapterPosition();
holder.checkbox.setChecked(b);
} else {
currentCheckedPosition = - 1 ;
}
notifyDataSetChanged();
}
});
holder.checkBox.setChecked(position == currentCheckedPosition);
}