Android RadioGroup监听器启动活动

时间:2016-01-13 21:59:02

标签: android listener android-radiogroup android-radiobutton

我需要编写哪些代码才能让我的监听器调出已检查的单选按钮?这是我的代码:

public class TabFragment1 extends Fragment {

    RadioGroup radioGroup;
    RadioButton radioButtonJa, radioButtonNee;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        radioGroup = (RadioGroup)v.findViewById(R.id.radioGroup);
        radioButtonJa = (RadioButton)v.findViewById(R.id.radio_hoogteverschillen_ja);
        radioButtonJa.setChecked(true);
        radioButtonNee = (RadioButton)v.findViewById(R.id.radio_hoogteverschillen_nee);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
        {
            public void onCheckedChanged(RadioGroup radioGroup, int checkedId)
            {
                boolean isChecked1 = radioButtonJa.isChecked();
                boolean isChecked2 = radioButtonNee.isChecked();
                if (isChecked1){
                    radioButtonJa.setChecked(true);
                    Toast.makeText(getActivity().getBaseContext(), "Ja", Toast.LENGTH_SHORT).show();
                }
                else if (isChecked2){
                    radioButtonNee.setChecked(true);
                    Toast.makeText(getActivity().getBaseContext(), "Nee", Toast.LENGTH_SHORT).show();
                }
                else{
                    Toast.makeText(getActivity().getBaseContext(), "Geen", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

启动我的应用时,它应该创建一个吐司,但它不会。它只在我第一次点击另一个单选按钮时创建一个。这也是布局文件中android:checked(true)的情况(而不是radioButtonJa.setChecked(true);)。打开应用程序时如何才能显示吐司?

1 个答案:

答案 0 :(得分:0)

        int radioButtonID = radioGroup.getCheckedRadioButtonId();
        View radioButton = radioGroup.findViewById(radioButtonID);
        int idx = radioGroup.indexOfChild(radioButton);

        RadioButton r = (RadioButton)  radioGroup.getChildAt(idx);
        String selectedtext = r.getText().toString();

        Toast.makeText(getApplicationContext(), selectedtext, Toast.LENGTH_SHORT).show();

在设置Radio Buttons的变量后立即将此代码放入onCreateView()方法中。 这样就可以了。

取自here