具有自定义布局和EditText的AlertDialog.Builder; 无法访问视图

我正在尝试使用EditText对象创建警报对话框。我需要以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对象?


[编辑]


因此,user370305和其他人指出了我应该使用的 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。


GCT1015
浏览 580回答 3
3回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android