最佳答案
我试图创建一个与 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
对象?
[edit]
因此,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
。
[/编辑]