【发布时间】:2019-10-01 01:21:51
【问题描述】:
我有一个由三个单选按钮 '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;
}
}
【问题讨论】:
-
只需使用 android:checked="true"
标签: android radio-button radio-group