【问题标题】:Create an alertdialog which include a list创建一个包含列表的警报对话框
【发布时间】:2021-08-17 11:01:54
【问题描述】:

如何在 AlertDialog 上创建一个列表,其中包含一些单选按钮,当我单击 AlertDialog 的项目时,执行类似 toast 的操作。

【问题讨论】:

    标签: java list radio-button android-alertdialog


    【解决方案1】:

    试试这个:

    //Setup the alert builder
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("Choose an animal");// add a radio button list
    String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
    int checkedItem = 1; // cow
    builder.setSingleChoiceItems(animals, checkedItem, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //Here you can implement Toast Message
        }
    });
    //Add OK and Cancel buttons
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //Handle when user clicks OK
        }
    });
    builder.setNegativeButton("Cancel", null); //Create and show the alert dialog
    AlertDialog dialog = builder.create();
    dialog.show();
    

    如果有帮助请告诉我:)

    【讨论】:

    • 一个问题:我这样做了,但我需要一些东西,例如这个 alertdialog 在底部|右下角只包含一个 ok 按钮,例如其中的 3 个单选按钮,当您单击其中一个按钮时,执行事件和警报对话框会自动关闭吗?
    • 好吧,那么只需删除行 builder.setNegativeButton("Cancel", null); //创建并显示警报对话框以删除取消按钮。要关闭 alertDialog,只需调用 dialog.dismiss() 或 dialog.close()
    • 我有一个问题:例如这些单选按钮是:动物、虎门、花卉。我想给他们不同的事件,例如当我点击动物吐司时:动物点击。当我点击鲜花吐司时:鲜花点击,当humen点击吐司时:humen点击了先生,我该怎么做?
    • 在 setSingleChoiceItems onClick 方法中,检查 which 变量。比如 if(which == 0) {Toast.makeText(MainActivity.this, "Clicked on horse", Toast.LENGTH_LONG).show();}
    • 如果我帮助了你,请点赞我的答案并接受它作为解决方案:) 谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多