【问题标题】:Know which RadioButton is checked on RadioGroup [duplicate]知道在 RadioGroup 上选中了哪个 RadioButton [重复]
【发布时间】:2018-09-13 03:32:13
【问题描述】:

我想知道检查了哪个RadioButton 执行操作。

但这不起作用。在日志中我有 ID -1

mradioGroup = (RadioGroup) rootView.findViewById(R.id.choix_plateforme);
        mradioGroupt = (RadioButton) rootView.findViewById(R.id.ps4);
        mradioGroupa = (RadioButton) rootView.findViewById(R.id.xbox);
        mradioGroupw = (RadioButton) rootView.findViewById(R.id.pc);

        int selectedId = mradioGroup.getCheckedRadioButtonId();
        Log.d(getClass().getName(), "Plateforme_Choix = " + selectedId);
        // find which radioButton is checked by id

        if(mradioGroupt.isChecked()) {
            string_plateforme = "one";
        } else if(mradioGroupa.isChecked()) {
            string_plateforme = "two";;
        } else if (mradioGroupw.isChecked()){
            string_plateforme = "oops";
        }
        else {
            string_plateforme = "wrong";
        }

我的if 声明也不起作用。

<RadioGroup
    android:id="@+id/choix_plateforme"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="horizontal">

    <RadioButton
        android:id="@+id/ps4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Playstation 4" />

    <RadioButton
        android:id="@+id/xbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="XBOX ONE" />

    <RadioButton
        android:id="@+id/pc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Ordinateur" />

</RadioGroup>

你能告诉我哪里错了吗?我不想要新代码,但如果可以的话,请向我解释我的错误。

【问题讨论】:

  • 您从没有选中的 RadioButton 开始。因此,如果用户真的点击了其中一个 RadioButton,您只会得到一个选中的 RadioButton。如果您始终希望至少选中一个 RadioButton,那么您可以通过编程方式或通过属性 android:checked="true" 设置其中一个已选中

标签: java android


【解决方案1】:

尝试设置 OnCheckedChangeListener 更改监听器:

        radiogroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId)
            {
                switch(checkedId)
                {
                case R.id.ps4:
                     Log.d(getClass().getName(), "Plateforme_Choix =ps4");
                    break;
                case R.id.xbox:
                    Log.d(getClass().getName(), "Plateforme_Choix =xbox");
                    break;
                case R.id.pc:
                    Log.d(getClass().getName(), "Plateforme_Choix =pc");
                    break;
                }
            }
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 2023-03-15
    • 2014-01-03
    相关资源
    最近更新 更多