【问题标题】:Access the layout of an AlertDialog访问 AlertDialog 的布局
【发布时间】:2021-12-06 20:02:57
【问题描述】:

这是在以下地址找到的示例:https://newbedev.com/how-to-add-a-check-box-to-an-alert-dialog。使用此代码,您可以创建一个带有复选框的 AlertDialog:

    public void dialog_box () {
      
        AlertDialog.Builder builder = new AlertDialog.Builder (this);
        builder.setTitle ("Choose some animals");
        builder.
// add a checkbox list
        String [] animals = {"horse", "cow", "camel", "sheep", "goat"};
        boolean [] checkedItems = {true, false, false, true, false};
        builder.setMultiChoiceItems (animals, checkedItems, new DialogInterface.OnMultiChoiceClickListener () {
            @Override
            public void onClick (DialogInterface dialog, int which, boolean isChecked) {
                // user checked or unchecked a box
            }
        });

// add OK and Cancel buttons
        builder.setPositiveButton ("OK", new DialogInterface.OnClickListener () {
            @Override
            public void onClick (DialogInterface dialog, int which) {
                // user clicked OK
            }
        });
        builder.setNegativeButton ("Cancel", null);

// create and show the alert dialog
        AlertDialog dialog = builder.create ();
        dialog.show ();
    }

我希望我可以访问该对话框的布局,以便能够执行与此类似的操作 (Checking Multiple Checkboxes in Android),这将允许我访问复选框:

for (int i = 0; i <ll.getChildCount (); i ++) {
    View v = ll.getChildAt (i);
    if (v instanceof CheckBox) {
        ((CheckBox) v) .setChecked (true);
    }
}

ll-> AlertDialog 的布局 提前致谢

【问题讨论】:

  • 您是在问如何检查AlertDialog 中的所有Checkboxes 吗?还是您真的需要访问它们?因为setMultiChoiceItems() 调用中的第二个参数决定了在对话框显示时检查哪些参数。您可以简单地将所有trues 传递到那里。
  • 我需要知道标记了哪些列表框
  • 您可以在其onClick() 方法中使用OnMultiChoiceClickListener 来做到这一点;例如,checkedItems[which] = isChecked;。在setPositiveButton()onClick() 中,您可以检查选择了哪些相同的数组。
  • @Mike 先生,请您解释一下
  • 每次选中或取消选中项目时,OnMultiChoiceClickListeneronClick() 方法都会运行。 which 参数告诉您它是数组中的哪个项目,isChecked 参数是不言自明的。如果您每次都更新原始的 checkedItems 数组——例如,checkedItems[which] = isChecked;——那么您可以简单地遍历该数组以查看检查了哪些项目:for (int i = 0; i &lt; checkedItems.length; i++) { if (checkedItems[i]) ... }

标签: android android-alertdialog android-checkbox


【解决方案1】:
  • 试试这样的东西
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(this);
View view = layoutInflaterAndroid.inflate(R.layout.your_layout, null);
builder.setView(view);

【讨论】:

  • 我需要知道标记了哪些列表框
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多