gpt4 book ai didi

android - 如何强制 RadioGroup 中的 ToggleButton 在第二次按下时保持选中状态?

转载 作者:行者123 更新时间:2023-12-04 18:10:02 24 4
gpt4 key购买 nike

我的 Activity 中有一个 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() 的相关 block :

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

如果我需要添加更多代码,请告诉我。谢谢!

最佳答案

下面这行应该和toggle click事件在同一个类中;

private RadioButton mBtnCurrentRadio;

切换点击事件(应该在activity中);

public void onToggle(View view) {

final ToggleButton mBtnToggle = (ToggleButton) view;

// select only one toggle button at any given time
if (mBtnCurrentToggle != null) {
mBtnCurrentToggle.setChecked(false);
}
mBtnToggle.setChecked(true);
mBtnCurrentToggle = mBtnToggle;

// app specific stuff ..
}

用于布局的 RadioGroup xml 代码;

<RadioGroup
android:id="@+id/toggleGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:orientation="horizontal" >

<ToggleButton
android:id="@+id/btn_Letter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="onToggle"
android:textOff="Letter"
android:textOn="Letter"
style="@style/toggleBtnStyle" />

<ToggleButton
android:id="@+id/btn_A4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="onToggle"
android:textOff="A4"
android:textOn="A4"
style="@style/toggleBtnStyle" />

<ToggleButton
android:id="@+id/btn_A3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="onToggle"
android:textOff="A3"
android:textOn="A3"
style="@style/toggleBtnStyle" />
</RadioGroup>

关于android - 如何强制 RadioGroup 中的 ToggleButton 在第二次按下时保持选中状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16235544/

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