AlertDialog与复选框在Android [英] AlertDialog with checkbox In android

查看:87
本文介绍了AlertDialog与复选框在Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android的新用户。我在一个应用程序,我需要显示一个对话框,其中用户可以选择多个项目。为此,我想在对话框中的每个项目添加一个复选框。

I am new to Android. I am working on an app in which I need to show a dialog in which user can select more than one item. For this I want to add a checkbox to each item in the dialog.

我阅读StackOverflow上的以下帖子:

I read following posts on StackOverflow:

如何在警报对话框中添加复选框

Android复选框对话框简单)

这些帖子之一描述了如何创建XML定义复选框,除了膨胀对话框,但我不能让它工作。 / p>

One of these posts describe how to create XML defining the checkbox in addition to inflating the dialog, but I could not get it to work.

推荐答案

在AlertDialog中添加复选框在博客中有很好的解释 在Android中使用复选框进行对话

您可以访问博客 AlertDialog With Android在Android中使用复选框

final CharSequence[] items = {" Easy "," Medium "," Hard "," Very Hard "};
// arraylist to keep the selected items
final ArrayList seletedItems=new ArrayList();

AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Select The Difficulty Level")
.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int indexSelected, boolean isChecked) {
        if (isChecked) {
            // If the user checked the item, add it to the selected items
            seletedItems.add(indexSelected);
        } else if (seletedItems.contains(indexSelected)) {
            // Else, if the item is already in the array, remove it
            seletedItems.remove(Integer.valueOf(indexSelected));
        }
    }
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int id) {
        //  Your code when user clicked on OK
        //  You can write the code  to save the selected item here
    }
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int id) {
        //  Your code when user clicked on Cancel
    }
}).create();
dialog.show();

这篇关于AlertDialog与复选框在Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆