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

When a view is used as template and id repeat, how can single checkbox be selected on click of its parent

我从数据库中接收了一系列数据,并将其显示在一个由复选框和其他一些选项组成的层中 views.In 事实上,我已经进行了控制自定义。 我的问题是如何在点击任何图层时打开该图层的复选框,其余的都关闭。

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();
        }
    });

}}

我的问题是,当您单击一个图层时,另一个图层的复选框被选中,但 return id 正确。

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

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

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

如果这不起作用:

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

  1. 使用回收站视图,您将获得点击项目的索引并从那里处理。 如果您从 db 获取条目并且您可能知道可能有多少条目,那么您的 UI 可能会变得太重。使用回收器视图将有助于提高性能