AlertDialog.Builder зі спеціальним макетом та EditText; не вдається отримати доступ до перегляду


101

Я намагаюся створити діалог попередження з 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об'єкт?

[редагувати]

Отже, користувач370305 та інші вказали на те, що я повинен використовувати 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.

[/ редагувати]

Відповіді:


238

editTextє частиною alertDialogверстки, тому просто доступ editTextз посиланням наalertDialog

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

Оновлення:

Тому що в кодовому рядку dialogBuilder.setView(inflater.inflate(R.layout.alert_label_editor, null));

inflaterє Null .

оновіть свій код, як показано нижче, і спробуйте зрозуміти кожен рядок коду

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:

Оскільки ви використовуєте об’єкт View, створений Inflater для оновлення компонентів інтерфейсу, ви можете безпосередньо використовувати setView(int layourResId)метод AlertDialog.Builderкласу, який доступний від API 21 і далі.


22
Ви також можете зробити це так:dialogBuilder.setView(R.layout.dialog_layout);
SiavA

4
@SiavA цей метод доступний лише у формі API 21.
Scaraux

Я намагався відобразити Dialog, і він не працював у RecyclerView, але цей.
Muneeb Mirza

Ви можете використовувати, getLayoutInflater()коли значення inflaterне визначено.
зворотний

1
@saigopi, коли ви перекриєте onClick, з'являться аргументи (діалогове вікно DialogInterface, int id). У цьому методі onClick просто передайте dialog.cancel ();
Мінко

29

Використовуйте цей

   AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    // Get the layout inflater
    LayoutInflater inflater = (activity).getLayoutInflater();
    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the
    // dialog layout
    builder.setTitle(title);
    builder.setCancelable(false);
    builder.setIcon(R.drawable.galleryalart);
    builder.setView(inflater.inflate(R.layout.dialogue, null))
    // Add action buttons
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {

                    }
                }
            });
    builder.create();
    builder.show();

слід builder.create().show();, ви можете перевірити builder.show();код для більш детальної інформації
Фан Ван Лінь

9

Ви можете написати:

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

Button button = (Button)dialogView.findViewById(R.id.btnName);

   button.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {

         //Commond here......

       }
   });

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

editText.setText("test label"); 

dialogBuilder.create().show();

3

Якщо хтось захоче його в Котліні:

val dialogBuilder = AlertDialog.Builder(this)
// ...Irrelevant code for customizing the buttons and title
val dialogView = layoutInflater.inflate(R.layout.alert_label_editor, null)
dialogBuilder.setView(dialogView)

val editText =  dialogView.findViewById(R.id.label_field)
editText.setText("test label")
val alertDialog = dialogBuilder.create()
alertDialog.show()

Повторно @ user370305 ігрового відповідь.


2

Змініть це:

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

до цього:

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

1
View v=inflater.inflate(R.layout.alert_label_editor, null);
alertDialog.setContentView(v);
EditText editText = (EditText)v.findViewById(R.id.label_field);
editText.setText("test label");
alertDialog.show();

1
/**
 * Shows  confirmation dialog about signing in.
 */
private void startAuthDialog() {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
    AlertDialog alertDialog = dialogBuilder.create();
    alertDialog.show();

    alertDialog.getWindow().setLayout(800, 1400);
    LayoutInflater inflater = this.getLayoutInflater();
    View dialogView = inflater.inflate(R.layout.auth_dialog, null);
    alertDialog.getWindow().setContentView(dialogView);
    EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
    editText.setText("test label");
}
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.