【问题标题】:How to read RadioButton state如何读取 RadioButton 状态
【发布时间】:2012-01-28 01:42:27
【问题描述】:

我有一个名为 options.xml 的 xml 文件 我用它来创建我的 AlertDialog。我还为 AlertDialog 添加了一个完成按钮。 当按下完成按钮时,将调用下面的 onClick 方法。但是,无论我在单击完成之前检查了哪个 RadioButton,我总是将第一个 RadioButton 设为选中,而将其他 RadioButton 设为未选中。 我假设我在下面做的只是读取 xml 值而不是实际的运行时值?那么如何读取真正的运行时值呢?

    public void onClick(DialogInterface arg0, int arg1) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) ;
            View layout = inflater.inflate(R.layout.options, null);
            RadioButton a1 = (RadioButton)layout.findViewById(R.id.radio0);
            RadioButton a2= (RadioButton)layout.findViewById(R.id.radio1);
            RadioButton a3 = (RadioButton)layout.findViewById(R.id.radio2);
            RadioButton a4 = (RadioButton)layout.findViewById(R.id.radio3);
            boolean b1 = a1.isChecked();
            boolean b2 = a2.isChecked();
            boolean b3 = a3.isChecked();
            boolean b4 = a4.isChecked();

    }

编辑:我使用的解决方案“谢谢,我没有检查第二个选项,但我发现 AlertDialog 有 findViewById ,这只是在创建对话框后调用它的问题。(不需要在 onCreate 或任何其他特殊功能)。您只需要记住在为对话框调用 show() 后调用 findViewById ,否则它会失效”

【问题讨论】:

    标签: android radio-button android-alertdialog


    【解决方案1】:

    没错,您正在读取它们的 xml 值,因为您试图在直接从 xml 膨胀的布局上查找 ViewById。

    如果 mContext 是 Activity,您可以使用 mContext.findViewById(..)。如果做不到这一点,请在 onCreateDialog(..) 中的某处而不是在 onClick(..) 中定义您的 RadioButton,然后使用这些来确定 isChecked()。

    这是一个类似的示例,我必须从 onClick(..) 方法中获取 EditText 的值。如果您需要 final 修饰符,Eclipse 应该会告诉您。这一切都在 onCreateDialog(..) 方法中。

    case FIRST_TRANSLATE:
            View view = mHost.getLayoutInflater().inflate(R.layout.first_translate, null);
            //Define your radiobuttons here
            final EditText mLanguage = (EditText) view.findViewById(R.id.editText1);
            b.setView(view)
            .setTitle(R.string.dialog_first_translate_title)
            .setPositiveButton(sOkay, new DialogInterface.OnClickListener() {
    
                @Override
                public void onClick(DialogInterface dialog, int arg1) {
                    //Retrieve their values here
                    mHost.getSharedPreferences(States.INTERNAL_PREFS, 0).edit().putString("deflang", mLanguage.getText().toString()).commit();
                    dialog.dismiss();
                }
    
            }).create();
    

    【讨论】:

    • 谢谢,我没有检查第二个选项,但我发现 AlertDialog 有 findViewById ,只需在创建对话框后调用它即可。 (不需要在 onCreate 或任何其他特殊函数中完成)。您只需要记住在为对话框调用 show() 后调用 findViewById,否则它不起作用。
    猜你喜欢
    • 1970-01-01
    • 2017-11-04
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 2019-08-16
    • 2021-11-14
    • 1970-01-01
    相关资源
    最近更新 更多