创建自定义AlertDialog?什么是根视图?

时间:2012-05-22 02:42:13

标签: android

我想做什么:

创建自定义警报对话框。按钮就像任何警报对话框,但上面是两个TextEdit输入框。我不想创建自定义对话框,而是创建自定义警报对话框

这是我正在尝试的#3: http://developer.android.com/guide/topics/ui/dialogs.html

它说:

AlertDialog.Builder builder;
AlertDialog alertDialog;

Context mContext = getApplicationContext();
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog,
                           (ViewGroup) findViewById(R.id.layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");


builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();

文档说:

View layout = inflater.inflate(R.layout.custom_dialog,
                           (ViewGroup) findViewById(R.id.layout_root));

其中第一个参数是布局资源ID,第二个参数是根视图的ID。

问题是我不知道布局根是什么?这是一个我将要在Activity中进行的对话。如果活动我应该使用布局ID吗? layout_root是否已从帽子中拉出来?

也尝试过:

  View layout = inflater.inflate(R.layout.my_custom_layout,
                                   (ViewGroup)   findViewById(android.R.id.content).getRootView());

结果空指针。

4 个答案:

答案 0 :(得分:34)

即使是较旧的问题,本文可能对搜索此答案的其他人有用:

Layout Inflation as Intended

  

如果您曾经使用过类似下面的代码   Android应用程序中的LayoutInflater:

inflater.inflate(R.layout.my_layout, null);
     

请继续阅读,因为你做错了,我想解释一下   你为什么。

... <强> BUT ...

  

每个规则都有例外

     

当然有一些情况可以让你真正证明null   通货膨胀期间的父母,但他们很少。出现了一个这样的例子   当您为要附加到的自定义布局充气时   的 AlertDialog 即可。考虑以下我们想要使用的示例   相同的XML布局,但将其设置为对话框视图:

AlertDialog.Builder builder = new AlertDialog.Builder(context);
View content = LayoutInflater.from(context).inflate(R.layout.item_row, null);

builder.setTitle("My Dialog");
builder.setView(content);
builder.setPositiveButton("OK", null);
builder.show();
     

这里的问题是AlertDialog.Builder支持自定义视图,但是   没有提供采用布局的setView()实现   资源;所以你必须手动充气XML。但是,因为   结果将进入对话框,该对话框不会公开其根视图   (事实上​​,它还不存在),我们无法访问最终版本   布局的父级,所以我们不能用它来进行通货膨胀。事实证明,   这是无关紧要的,因为AlertDialog将删除任何LayoutParams   无论如何都要用match_parent替换它们。

本文解释了为什么 应该在大多数其他情况下提供父ViewGroup而不是Dialog构建。

答案 1 :(得分:1)

确定。文档中的根视图引用自定义布局中的元素。因此,自定义布局将具有称为根视图的最外层视图。你需要给它一个Id,而不是你可以传递给它,如图所示。因此,第一个参数是自定义视图id,第二个参数是自定义视图中根布局元素的id。

 View layout = inflater.inflate(R.layout.custom_dialog,
                       (ViewGroup) findViewById(R.id.layout_root));

因此,在上面的文档中给出的示例中,R.id.layout_root引用了您提供的id,例如custom_dialog布局中最外面的LinearLayout。

答案 2 :(得分:0)

你试过这个吗?

View layout = inflater.inflate(R.layout.custom_dialog,null);

答案 3 :(得分:0)

builder.setView(layout);
layout.getRootView();

应提供LinearLayout