gpt4 book ai didi

具有自定义绑定(bind)逻辑的 Android 双向数据绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 00:56:14 25 4
gpt4 key购买 nike

我使用 android 数据绑定(bind)库,我有一个带复选框的布局,我需要使用自定义检查逻辑 (layout)。

有没有一种方法可以创建这样的绑定(bind),选中其中一个框会导致其余框取消选中?什么是最好的方法?

最佳答案

我建议如下:

  1. 为复选框设置一个通用的 OnClickListener
  2. 通过 XML 分配监听器(不是必需的,但显然更好)
  3. 每次选中一个复选框时循环检查复选框,并取消选中其他复选框。

XML

<LinearLayout
android:id="@+id/parent"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<CheckBox android:id="@+id/checkbox_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1"
android:onClick="onCheckboxClicked"/>

<CheckBox android:id="@+id/checkbox_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2"
android:onClick="onCheckboxClicked"/>

</LinearLayout>

Activity

public void onCheckboxClicked(View clickedView)
{
LinearLayout parent = (LinearLayout) findViewById(R.id.parent);
for (int i=0; i < parent.getChildCount(); i++)
{
View view = parent.getChildAt(i);
if (view instanceof CheckBox)
{
CheckBox checkbox = (CheckBox) view;
if (checkbox.isChecked() && !checkbox.equals(clickedView)) {
checkbox.setChecked(false);
}
}
}
}

显然,您可以创建一个名为 CheckBoxGroup 的自定义 ViewGroup,它接收复选框并自动实现此流程。但我认为没有必要,它会使事情复杂化。而且也不会那么灵活,因为复选框必须全部在其中。

关于具有自定义绑定(bind)逻辑的 Android 双向数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40118118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com