当一个视图被用作模板和id重复时,如何在单击其父项时选中单个复选框



我正在从数据库接收一系列数据,并将其显示在一个由复选框和其他一些视图组成的层中。事实上,我已经制定了一个控制性的习惯。我的问题是,当点击任何一层时,我如何打开该层的复选框,而其余的都关闭了

public class myclass extends LinearLayout {
LinearLayout linear;
public int id;
public static ImageView pic;
public static TextView titlepro;
public static CheckBox rdb;
public myclass(Context context) {
super(context);
init(context);
}
public myclass(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public myclass(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
public void init(Context context){
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.linear,this,true);
linear=(LinearLayout)findViewById(R.id.linear2);
pic=(ImageView)view.findViewById(R.id.pic);
titlepro=(TextView)view.findViewById(R.id.txt1);
rdb=(CheckBox)view.findViewById(R.id.rdb1);
rdb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
}
}
});
linear.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (rdb.isChecked()){
rdb.setChecked(false);
}else {
rdb.setChecked(true);
}
Toast.makeText(G.context,id+"",Toast.LENGTH_LONG).show();
}
});
}}

我的问题是,当你点击一个图层时,会选中另一个图层的复选框,但会正确返回id。

问题是因为您使用的id对所有复选框都是相同的。

有几种方法可以解决这个问题:

1.linear=(LinearLayout(findViewById(R.id.liner2(;->linear=(LinearLayout(view.findViewById(R.id.linear2(;

如果不起作用:

2.考虑创建一个新片段,该片段在一个层中具有所有视图。然后,您可以将其中的多个添加到您的视图中。在类的一侧,考虑处理层单击事件。

  1. 使用回收器视图,然后您将获得点击的项目索引并从中进行处理。如果您正在从数据库中获取条目,并且您可能知道可能有多少条目,那么您的UI可能会变得太重。使用回收器视图将有助于提高性能

最新更新