【发布时间】:2016-04-21 16:06:37
【问题描述】:
我的活动中有一个 RadioGroup,其中包含四个具有自定义背景的 ToggleButton。我希望用户能够一次选择任何一个按钮,并且永远不应该选择任何按钮,但即使它在 RadioGroup 中并且一切正常,选择已经选择的 ToggleButton 会取消选择它,不留下按钮被选中。
如果用户再次点击 ToggleButton,如何强制它保持选中状态?
我的 XML:
<RadioGroup
android:id="@+id/radio_group"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" />
我的 onCreate() 的相关块:
radioGroup = (RadioGroup) findViewById(R.id.radio_group);
radioGroup.setOnCheckedChangeListener(onRadioGroupClickListener);
for (int index = 0; index < OPTIONS.length; index++) {
ToggleButton button = new ToggleButton(this);
button.setId(index);
button.setText(OPTIONS[index]);
button.setTextOn(OPTION[index]);
button.setTextOff(OPTIONS[index]);
button.setChecked(index == 0); // Set to first option by default
button.setButtonDrawable(Color.TRANSPARENT);
button.setBackgroundResource(R.drawable.selector);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
RadioGroup parent = (RadioGroup) view.getParent();
ToggleButton button = (ToggleButton) view;
TimesheetLog.d("View is checked: " + button.isChecked());
parent.check(button.getId());
currentSelection = view.getId();
}
});
radioGroup.addView(button);
}
如果我需要添加更多代码,请告诉我。谢谢!
【问题讨论】:
-
嗯,你为什么不在你的单选组中使用单选按钮?他们按照你想要的方式行事
-
我在让任何东西工作时遇到了很多麻烦,据我所知,单选按钮看起来并不像真正的按钮。我错了吗?我以为文字总是偏题...
-
它们看起来像单选按钮 :-) 是的,文本偏向一边。你看this question了吗?
-
是的,这就是我基于我的代码的答案 - 唯一的问题是你可以没有选择,但我想始终保持至少一个选择。顺便说一句,感谢您的回复!
标签: android togglebutton