【发布时间】:2014-03-08 00:38:33
【问题描述】:
我的活动中有四个复选框,
[全部,选项 1,选项 2,选项 3]。
我的预期功能是在加载活动时默认选择全部,如果您选择任何其他选项,[全部]将被取消选中,如果您选择了任何其他选项并且您再次选择[全部],它将取消选中其他选项。
我有这种工作,默认选择全部,但是当我选择其中一个选项时;根据需要取消选中所有选项,但直到我第二次按下复选框后才会选中选中的复选框。
类似地,如果我选中了选项 2 和 3,然后我选择了全部:选项 2 和 3 未选中,但直到我第二次按下它才会检查全部。
这是我的 onCreateMethod
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selection);
all = (CheckBox) findViewById(R.id.All);
option1 = (CheckBox) findViewById(R.id.option1);
option2 = (CheckBox) findViewById(R.id.option2);
option3 = (CheckBox) findViewById(R.id.option3);
IfAllChecked();
optionOneSelectedUnCheckedAll();
optionTwoSelectedUnCheckedAll();
optionThreeSelectedUnCheckedAll();
}
这是我选择“全部”时的代码:
private void IfAllChecked() {
all.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (option1.isChecked()) {
option1.setChecked(false);
}
if (option2.isChecked()) {
option2.setChecked(false);
}
if (option3.isChecked()) {
option3.setChecked(false);
}
}
}
);
}
当其中一个选项被选中时的代码
private void optionOneSelectedUnCheckedAll() {
option2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (all.isChecked()) {
all.setChecked(false);
}
}
}
);
}
这是我的布局,我在这里将 All 设置为 true。
<LinearLayout
android:id="@+id/UnitName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<CheckBox
android:id="@+id/All"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="All"
android:checked="true" />
<CheckBox
android:id="@+id/option1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dun L"/>
<CheckBox
android:id="@+id/option2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Blackrock" />
<CheckBox
android:id="@+id/option3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dundrum" />
</LinearLayout>
希望有人能理解我试图解释的内容。
【问题讨论】:
-
您是否也有代码在您的代码中设置包裹在这些函数(IfAllChecked()、optionOneSelectedUnCheckedAll())中的 OnCheckedChangeListener?
-
您的帖子有点混乱。您用四个复选框描述了一个 Activity,但您的代码显示了 六个 复选框。
-
抱歉,我发布这个问题时已经很晚了,我已经更改了变量的名称,因为它更容易让人理解,我已经编辑了我的问题以正确更改所有名称跨度>
-
好的,只要你改了合适的变量名,我的回答应该不错。如果您有任何问题或无法正常工作,请让我知道。