【发布时间】:2014-03-26 08:48:03
【问题描述】:
我正在尝试使用 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。
[/编辑]
【问题讨论】:
标签: android