カスタムレイアウトと EditText を使用した AlertDialog.Builder。ビューにアクセスできません。質問する

カスタムレイアウトと 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

[/編集]

ベストアンサー1

editTextalertDialogレイアウトeditTextの一部なので、alertDialog

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

アップデート:

コード行にdialogBuilder.setView(inflater.inflate(R.layout.alert_label_editor, null));

inflaterヌル

以下のようにコードを更新し、各コード行を理解してみてください。

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

アップデート2:

Inflater によって作成された View オブジェクトを使用して UI コンポーネントを更新している場合は、API 21 以降で使用できるクラスsetView(int layourResId)のメソッドを直接使用できます。AlertDialog.Builder

おすすめ記事