本文介绍了AlertDialog.Builder自定义布局和EditText上;不能访问视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个EditText对象的警告对话框。我需要以编程方式设置的EditText的初始文本。下面是我的。

I am trying to create an alert dialog with an EditText object. I need to set the initial text of the EditText programmatically. Here's what I have.

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对象?

What do I need to change so that I can have a valid EditText object?

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

So, it was pointed out by user370305 and others that I should be using alertDialog.findViewById(R.id.label_field);

不幸的是这里还有另外一个问题。显然,设置在AlertDialog的内容视图导致程序崩溃在运行时。你必须对制造商进行设置。

Unfortunately there is another issue here. Apparently, setting the content view on the AlertDialog causes the program to crash at runtime. You have to set it on the builder.

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。

Unfortunately, when you do this, alertDialog.findViewById(R.id.label_field); now returns null.

[/编辑]

推荐答案

EDITTEXT alertDialog 的一部分布局因此,只要接入 EDITTEXT alertDialog

editText is a part of alertDialog layout so Just access editText with reference of alertDialog

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

更新:

由于在code线 dialogBu​​ilder.setView(inflater.inflate(R.layout.alert_label_editor,NULL));

充气

更新code如下图所示,并尝试去了解每一个code线

update your code like below, and try to understand the each code line

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();

这篇关于AlertDialog.Builder自定义布局和EditText上;不能访问视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:38