如何实现自定义AlertDialog视图

115

Android AlertDialog文档中,它提供了以下设置AlertDialog自定义视图的指示和示例:

如果您想显示更复杂的视图,请查找名为“body”的FrameLayout并将其添加到其中:

FrameLayout fl = (FrameLayout) findViewById(R.id.body);
fl.add(myView, new LayoutParams(FILL_PARENT, WRAP_CONTENT));

首先,很明显add()是一个笔误,应该是addView()

对于第一行使用的R.id.body,我感到困惑。它似乎是AlertDialog的body元素...但我不能在我的代码中输入它,因为它会导致编译错误。R.id.body在哪里定义或分配了呢?

这是我的代码。我尝试在builder上使用setView(findViewById(R.layout.whatever),但它没有工作。我猜测是因为我没有手动填充它?

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title")
    .setCancelable(false)
    .setPositiveButton("Go", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int id) {
        EditText textBox = (EditText) findViewById(R.id.textbox);
        doStuff();
    }
});

FrameLayout f1 = (FrameLayout)findViewById(R.id.body /*CURRENTLY an ERROR*/);
f1.addView(findViewById(R.layout.dialog_view));

AlertDialog alert = builder.create();
alert.show();

要在对话框上查找和使用对象,请按照以下四个步骤进行:https://dev59.com/n2kv5IYBdhLWcg3w1kSr#18773261 - Sara
6
一句话回答:在构建器中添加.setView(getLayoutInflater().inflate(R.layout.dialog_view, null))。感谢下面的Sergio Viudes。 - 1''
12个回答

1

将ID更改为android.R.id.custom后,我需要添加以下内容才能使视图显示:

((View) f1.getParent()).setVisibility(View.VISIBLE);

然而,这导致新的视图在没有背景的大父视图中呈现,将对话框分为两个部分(文本和按钮,新视图位于其中间)。最终,我通过将我的视图插入到消息旁边来达到想要的效果:
LinearLayout f1 = (LinearLayout)findViewById(android.R.id.message).getParent().getParent();

我通过使用View.getParent()和View.getChildAt(int)探索View树找到了这个解决方案。然而,对于这两种方法都不是很满意。Android文档中都没有提到这些内容,如果AlertDialog的结构发生改变,这个解决方案可能会失效。

0

这对我有效! 不要忘记实现监听器。

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.add_employee, null);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接