【问题标题】:How to know which radiobutton was clicked when ok button is clicked in alertdialog?在alertdialog中单击确定按钮时如何知道单击了哪个单选按钮?
【发布时间】:2012-03-22 17:30:44
【问题描述】:

我有下面的 alertdialog 代码:

    AlertDialog.Builder helpBuilder = new AlertDialog.Builder(this);
    helpBuilder.setTitle("Options");
    helpBuilder.setMessage("Choose Your Option");

    LayoutInflater inflater = getLayoutInflater();
    View radioButtonLayout = inflater.inflate(R.layout.popuplayout, null);
    byNameRadioButton = (RadioButton) findViewById(R.id.byname);
    byIdRadioButton = (RadioButton) findViewById(R.id.byid);
    helpBuilder.setView(radioButtonLayout);
    helpBuilder.setPositiveButton("Ok",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                     Toast.makeText(Tab1Activity.this,
                     "Ok button is clicked", Toast.LENGTH_LONG)
                     .show();


                    }


                }
            });

    AlertDialog helpDialog = helpBuilder.create();
    helpDialog.show();

我想知道单击确定按钮时单击了哪个单选按钮?? 需要帮助。 谢谢!

【问题讨论】:

    标签: android radio-button android-alertdialog


    【解决方案1】:

    为什么不使用带有单选按钮的 Dialog 的默认实现,您可以在这里找到:Dialogs。你不需要写任何额外的代码,你会得到你需要的! :) 这是一个例子:

    final CharSequence[] items = {"By Score", "By Name", "By Id"};
    
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Options");
    builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
        }
    });
    AlertDialog alert = builder.create();
    

    【讨论】:

    • 没错,默认版本比你用OK按钮更有用。
    • 为什么这段代码不起作用?? okButton = (Button) findViewById(R.id.ok); okButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Above code u mention } });点击ok按钮,alertdialog应该会出现,但没有任何反应。
    • 我写的确切代码:okButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { final CharSequence[] items ={ "ByScore", "ByName", "ById" }; AlertDialog.Builder builder =new AlertDialog.Builder(Tab1Activity.this); builder.setTitle("Options"); builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); } }); AlertDialog alert = builder.create(); }});
    • 因为您需要致电alert.show(); 以便显示警报对话框。我给你的代码只创建了对话框,没有显示它:)
    猜你喜欢
    • 2021-05-17
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多