如何在AlertDialog.Builder上调用findViewById?

17

我正在尝试使用这段代码获取AlertDialog中的TextView引用:

AlertDialog.Builder logoutBuilder = new AlertDialog.Builder(getActivity());      
TextView alertTextView = (TextView) logoutBuilder.findViewById(android.R.id.message);
alertTextView.setTextSize(40);

但是我在findViewById处得到了编译器错误:

Cannot cast from AlertDialog.Builder to Dialog
The method findViewById(int) is undefined for the type AlertDialog.Builder

2个回答

28

按照以下方式从AlertDialog.Builder中创建对话框:

AlertDialog alert = builder.create();

然后,从警报中,您可以调用findViewById:

TextView alertTextView = (TextView) alert.findViewById(android.R.id.message);
alertTextView.setTextSize(40);

1
如果我这样做,就无法访问TextView,它们会显示为空。 - Lv99Zubat
17
没事了,我需要在调用.show()之后搜索TextView,然后它就可以工作了。谢谢你的回答,因为它引导我找到了解决方法。 - Lv99Zubat
View v = inflater.inflate(R.layout.activity_main, null); 会产生一个警告。使用 View.inflate(..., null, false) 只是隐藏了警告,但并没有解决问题。正确的方法是使用 builder.setView(R.layout.edit_account_dialog); dialog = builder.create(); 但是只有在活动调用 dialog.show() 后才能使用 findViewById;这又引起了另一个问题:对话框的 findViewByIdshow() 之前不可用,而在 show() 之后也不容易调用。顺便说一下,在 dialog.show() 后立即在活动中调用 findViewById 不是一个好的做法。 - JarsOfJam-Scheduler
你救了我的命,兄弟,谢谢。 - GeneCode

5

目前被认可的答案对我无效:它给了我一个空的TextView对象。相反,我需要从我膨胀的View中调用findViewById

AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
View v = getLayoutInflater().inflate(R.layout.view_dialog, null);
builder.setView(v);

现在,我可以使用v的findViewById找到TextView:
TextView card_info = v.findViewById(R.id.view_card_info_card_num);

稍后,我调用builder.show()来显示AlertDialog。
我觉得奇怪的是,被接受的答案对我没有用。它似乎符合文档要求。然而,我必须以这种方式处理它。

我认为它没有起作用是因为您使用了自定义对话框布局,而不是使用默认布局。他尝试使用 android.R.id.message 获取 TextView,这意味着使用了原始的对话框布局。 - DemoDemo

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