以编程方式将控件添加到自定义对话框



我想显示一个对话框,上面有~50个自定义控件(切换按钮)。因此,最好的方法是以编程方式将它们添加到循环中。我试图用包含唯一一个 GroupView 元素的布局制作一个 dilog:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:background="#AAAAAA"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <ViewGroup
        android:layout_height="500dp"
        android:layout_width="500dp"
        android:id="@+id/dlg_view"/>
</LinearLayout>

然后只需使用以下方法在其中添加我的控件:onCreateDialog(...) 方法:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
builder.setView(inflater.inflate(R.layout.geomap_menu, null))
          .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int id) {
                 // sign in the user ...
              }
          })
          .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                  //LoginDialogFragment.this.getDialog().cancel();
              }
});
Dialog res = builder.create();
ViewGroup dlgView = (ViewGroup)res.findViewById(R.id.dlg_view);
MyControl myControl = new MyControl(this);
dlgView.add(myControl);

但它不能以这种方式工作(它抛出 InflateException)。我做错了什么?

代码中的问题非常明显:

  • 在您的布局文件中,您使用ViewGroup它是一个抽象类(Android 中所有布局的根),并且无法实例化,因此它很可能是您谈论的膨胀异常的原因。使用ViewGroup的一个子类,如LinearLayoutRelativeLayout等,哪一个更适合你。

  • 即使在进行了我在上面写的修改后,您的代码仍然可以机器人工作。首先,ViewGroup类没有add方法,您可能指的是addView方法之一。其次,dlgView将被null,因为此时Dialog未显示,因此没有要查找View。您可以通过在其中一个视图上发布Runnable来延迟设置视图,直到显示Dialog

    final Dialog res = builder.create();
    oneOfYourViews.post(new Runnable() {
        @Override
        public void run() {
            ViewGroup dlgView = (ViewGroup) res.findViewById(R.id.dlg_view);
            MyControl myControl = new MyControl(context);
            dlgView.addView(myControl);             
        }
    });
    

代码添加:

View contentView = inflater.inflate(R.layout.geomap_menu, null)
ViewGroup dlgView = (ViewGroup) contentView.findViewById(R.id.dlg_view);
MyControl myControl = new MyControl(this);
dlgView.addView(myControl); // or add the other views in the loop as many as you want
builder.setView(contentView);
// rest of your code

最新更新