我正在try 创建一个带有EditText个对象的alert 对话框.我需要以编程方式设置EditText的初始文本.这是我的.

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
AlertDialog alertDialog = dialogBuilder.create();
LayoutInflater inflater = this.getLayoutInflater();
alertDialog.setContentView(inflater.inflate(R.layout.alert_label_editor, null));
EditText editText = (EditText) findViewById(R.id.label_field);
editText.setText("test label");
alertDialog.show();

我需要更改什么才能拥有有效的EditText对象?

[编辑]

因此,用户370305和其他人指出,我应该使用alertDialog.findViewById(R.id.label_field);

不幸的是,这里还有另一个问题.显然,将内容视图设置为AlertDialog会导致程序在运行时崩溃.你必须把它设置在生成器上.

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
dialogBuilder.setView(inflater.inflate(R.layout.alert_label_editor, null));
AlertDialog alertDialog = dialogBuilder.create();
LayoutInflater inflater = this.getLayoutInflater();
EditText editText = (EditText) alertDialog.findViewById(R.id.label_field);
editText.setText("test label");
alertDialog.show();

不幸的是,当你这样做时,alertDialog.findViewById(R.id.label_field);现在返回null.

[/编辑]

推荐答案

editTextalertDialog布局的一部分,因此只需参考alertDialog访问editText

EditText editText = (EditText) alertDialog.findViewById(R.id.label_field);

Update:

因为在代码行dialogBuilder.setView(inflater.inflate(R.layout.alert_label_editor, null));

inflater等于Null.

如下所示更新您的代码,并try 理解每个代码行

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);

EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
editText.setText("test label");
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();

Update 2:

当您使用充气机创建的视图对象来更新UI组件时,您可以直接使用AlertDialog.Builder类的setView(int layourResId)方法,该方法可从API 21及更高版本获得.

Android相关问答推荐

Jetpack Compose和Android Studio中的普通设计工具有什么不同?

Android系统应用程序启用编程以太网网络共享

如何将我的Android应用程序(Kotlin)中的图像分享给其他应用程序?

如何从URI中获取图像大小

为什么我有多个Player实例?

如何在C++中使用JNI_GetCreatedJavaVMs调用Java代码

如何在我的sqlite数据库中获取某个玩家的分数

同样的参数值下,为什么requiredSizeIn不等于requiredWidthIn + requiredHeightIn?

修复报错 RecyclerView: No adapter attached;跳过布局

如何在 Jetpack Compose 中对数据类进行 Parcelize

如何仅使用您的 Android 应用程序定位平板电脑?

如何在 Jetpack Compose 中创建无限pager

修复错误 Invariant Violation: requireNativeComponent: "RNSScreenStackHeaderConfig" was not found in the UIManager

Jetpack compose 为网络检索视频帧导致延迟

从 Firebase 云存储中获取照片会导致 Android Jetpack Compose 闪烁

新的内部测试应用程序版本不适用于测试人员,即使它说它们是

在 Compose 中使用 DeepLink 会导致无法向后导航

可组合的 fillMaxSize 和旋转不起作用

将生成的 AAR 与 Composables 一起使用时未解决的参考

如何将私有 mutableStateOf 分配给 Android Jetpack 中的 State 变量?