如何在AlertDialog.Builder上调用findViewById?

Pin*_*ton 8 android android-alertdialog

我试图得到一个参考TextViewAlertDialog使用此代码:

AlertDialog.Builder logoutBuilder = new AlertDialog.Builder(getActivity());      
TextView alertTextView = (TextView) logoutBuilder.findViewById(android.R.id.message);
alertTextView.setTextSize(40);
Run Code Online (Sandbox Code Playgroud)

但我收到编译器错误findViewById:

Cannot cast from AlertDialog.Builder to Dialog
The method findViewById(int) is undefined for the type AlertDialog.Builder
Run Code Online (Sandbox Code Playgroud)

Rom*_*naV 19

从AlertDialog.Builder创建对话框,如下所示:

AlertDialog alert = builder.create();
Run Code Online (Sandbox Code Playgroud)

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

TextView alertTextView = (TextView) alert.findViewById(android.R.id.message);
alertTextView.setTextSize(40);
Run Code Online (Sandbox Code Playgroud)

  • nvm,我需要搜索textview AFTER .show()被调用.然后它奏效了.谢谢,因为这个答案引导我. (11认同)

cur*_*rge 5

当前接受的答案对我不起作用:它给了我一个空的 TextView 对象。findViewById相反,我需要从我膨胀的视图中调用。

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

现在,我可以使用 v 的 findViewById 找到 TextView:

TextView card_info = v.findViewById(R.id.view_card_info_card_num);
Run Code Online (Sandbox Code Playgroud)

稍后,我调用builder.show()以显示 AlertDialog。

我发现奇怪的是接受的答案对我不起作用。它看起来与文档一致。尽管如此,我还是不得不这样对待它。