gpt4 book ai didi

android - 如何从单选组中获取默认选择的单选按钮?

转载 作者:行者123 更新时间:2023-11-29 23:10:00 33 4
gpt4 key购买 nike

我有一个由三个单选按钮组成的单选组 'yes','no','do not know'。我将 android:checkedButton="@id/r3" 设置为默认选择第三个单选按钮。我已经为单选组设置了 setOnCheckedChangeListener,它会在从 UI 中选择任何单选按钮时被调用。

我想在 onCreate 中为默认选中的单选按钮调用监听器,因为我正在对默认选中的代码执行一些值设置。

是否有可能在 onCreate 中获取单选组中默认选中的单选按钮并执行一些操作,稍后 setOnCheckedChangeListener 将处理来自 UI 的单选按钮

<RadioGroup
android:id="@+id/rg1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checkedButton="@id/r3"
android:orientation="horizontal"
android:weightSum="3">

<RadioButton
android:id="@+id/r1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Yes"
android:textColor="@color/fontBlackEnable" />

<RadioButton
android:id="@+id/r2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="No"
android:textColor="@color/fontBlackEnable" />

<RadioButton
android:id="@+id/r3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:checked="true"
android:text="@string/do_not_know" />

</RadioGroup>
public class MyFragment extends Fragment {

View rootView;
Context context;
RadioGroup mRadioAns3;



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
rootView = inflater.inflate(R.layout.my_fragment, container, false);
context = container.getContext();
mRadioAns3 = rootView.findViewById(R.id.rg1);

//Todo: get default selected radiobutton and show toast on load of fragment


mRadioAns3.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Toast.makeText(context,((RadioButton) rootView.findViewById(checkedId)).getText() ,Toast.LENGTH_LONG ).show();
}
});

return rootView;
}


}

最佳答案

if(gender.getCheckedRadioButtonId()==-1)
{
Toast.makeText(mContext, "Please select Gender", Toast.LENGTH_SHORT).show();
}
else
{
// get selected radio button from radioGroup
int selectedId = gender.getCheckedRadioButtonId();
// find the radiobutton by returned id
selectedRadioButton = (RadioButton)findViewById(selectedId);
Toast.makeText(mContext, selectedRadioButton.getText().toString()+" is selected", Toast.LENGTH_SHORT).show();
}

关于android - 如何从单选组中获取默认选择的单选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56123236/

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