【问题标题】:Android : How to disable one item in AlertDialog with MultiChoiceItemsAndroid:如何使用 MultiChoiceItems 禁用 AlertDialog 中的一项
【发布时间】:2016-06-30 11:38:30
【问题描述】:

我用以下代码创建了一个对话框:

final CharSequence[] items        = {" One ", " Two ", " Three "};

AlertDialog dialog = new AlertDialog.Builder(this)
            .setTitle("Title1")
            .setMultiChoiceItems(items, null, null)
            .setPositiveButton("CLOSE", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    Log.e("1k", "count : " + ((AlertDialog) dialog).getListView().getChildCount());

                }
            }).show();
    ListView lw = dialog.getListView();
    //lw.getChildAt(0).setEnabled(false);
    Log.e("1k", "count : " + lw.getChildCount());

这会创建一个对话框。 当我单击“关闭”按钮时,我可以在日志中看到“3”的输出。 到目前为止一切顺利,“items”数组中有 3 个字符串。

在“show()”之后调用的最后一行代码在日志中给了我“0”。

我想要做的是禁用列表中的第一项,但此代码抛出 NullPointerException 因为“getChildAt(0)”返回 null:

dialog.getListView().getChildAt(0).setEnabled(false);

如何禁用对话框列表中的第一个项目?

(以及为什么 getChildCount() ..

.. 在 show() 之后调用时返回 0 而不是 3?

.. 在 PositiveButton 的 onclick 中按预期返回 3 ? )

【问题讨论】:

  • 而不是 setMultiChoiceItems 在您的适配器实现中使用 setAdapter ... 覆盖 ListAdapter 接口 ...
  • 我试过这个,但外观和感觉不是原生的,即使使用 android.R.layout.select_dialog_multichoice 作为布局(我猜这不是材料之一;视图是方式太大了。即使我找到 Lollipop+ 使用的正确布局,它也不会向前兼容)

标签: android checkbox


【解决方案1】:

看看下面的代码是否有帮助:

final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
            MainActivity.this,
            android.R.layout.select_dialog_singlechoice);
    arrayAdapter.add("One");
    arrayAdapter.add("Two");
    arrayAdapter.add("Three");


AlertDialog dialog = new AlertDialog.Builder(this)
        .setTitle("Title1")
        .setPositiveButton("CLOSE", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        }).show();

dialog.setAdapter(
            arrayAdapter,
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int position) {
                    // no event on first position
                    if (position!= 0) {
                    }
                }
            });

【讨论】:

  • 但是这样item1仍然会被启用,并且我必须禁用列表中的第一个项目以表明item1被包含但用户不能更改它。
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多