如何查找已单击复选框的类



>我有一个具有以下属性的"ChecklistItem"类:

private CheckBox checkBox;
private ImageButton noteButton;
private TextView vitalField;

我的复选框有一个onClick Listener。现在的问题是,当我单击该复选框并调用OnClick()方法时,我如何确定该复选框属于哪个清单项?

每当我单击复选框时,我都想将复选框所属的ChecklistItem添加到数组中,但OnClick()只知道调用它的复选框。

我该如何解决这个问题?

好的,

所以这个答案是根据我们的"长时间讨论"

假设您要创建列表的 - 重新可用 - 视图,并且您编写了一个名为 list_item 的单独 XML 布局文件,如下所示:

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/checkbox"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/text_view"/>

所以现在让我们假设您在活动或片段中,或者您想托管视图的任何地方,现在我必须指出这只是一个例子,通常在这种情况下您需要列表视图,但我对您的应用程序的详细信息很少,所以我将保持简单

假设您有一个垂直线性布局,并且想要向其添加这些"行",则每行代表一个自定义视图

    LinearLayout layout = findViewById(R.id.layout);
    LayoutInflater inflater = LayoutInflater.from(this); // This inflater is responsible of creating instances of your view
    View myView = inflater.inflate(R.layout.list_item, layout, false); // This view objects is the view you made in your xml file
    CheckBox checkBox = (CheckBox) myView.findViewById(R.id.checkbox);
    TextView textView = (TextView) myView.findViewById(R.id.text_view);
    checkBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //if checkbox is checked enable textview for example
            // here you have a reference to all the views you just created
            // Weather you want to save them in a class together that's up to you and your app's logic
        }
    });
    layout.addView((myView));

如果列表可能超过屏幕高度,则可能需要在滚动视图中包装线性布局。

顺便说一句:ListView 只是一种通过定义您希望每行的显示方式来自动执行此操作的巧妙方法,当然它会为您管理您的视图并在它们进入屏幕时回收它们,但我只是想指出这个概念。

希望这对你有帮助

最新更新