Android — извлечение ввода текста из диалогового окна alertbuilder

#java #android #xml #android-alertdialog

#java #Android #xml #android-alertdialog

Вопрос:

У меня есть представление, определенное в XML-файле. Он содержит два поля Edittext (среди прочего, например, текст)

Я использую AlertBuilder для запуска диалогового окна, в котором пользователь вводит текст (например, имя пользователя и пароль) в оба поля edittext. Когда я пытаюсь извлечь строки и отправить их в Login(), обе строки имеют значение null. Что происходит?

Похоже, что каким-то образом строковые данные не сохраняются?

Вот когда я показываю диалоговое окно в своем приложении:

 SignInDialog.show(ScreenMain.this, 
                                "Login", 
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                        LayoutInflater inflater = (LayoutInflater) ScreenMain.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                                        View layout = inflater.inflate(R.layout.screen_dialog_login, null);
                                        LogIn(((EditText) layout.findViewById(R.id.screen_dialog_login_username_edit)).getText().toString(),
                                                        ((EditText) layout.findViewById(R.id.screen_dialog_login_password_edit)).getText().toString());

                                    }
                                }, 
                                "Cancel", 
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                    }
                                });
  

Вот класс, который я использую для создания экземпляра диалогового окна:

 /* login dialog*/
static class SignInDialog {

    public static void show(Context context, String positiveText, DialogInterface.OnClickListener positive, String negativeText, DialogInterface.OnClickListener negative){
        AlertDialog.Builder builder;

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.screen_dialog_login, null);

        builder = new AlertDialog.Builder(context);
        builder.setView(layout);
        if(positive != null amp;amp; positiveText != null){
            builder.setPositiveButton(positiveText, positive);
        }
        if(negative != null amp;amp; negativeText != null){
            builder.setNegativeButton(negativeText, negative);
        }

        builder.create().show();

    }
}
  

Ответ №1:

Чтобы раздуть макет, нужно создать его новый экземпляр. (Вы не получаете ссылку на существующий экземпляр.) Итак, в вашем onClick вы создаете новую копию макета, и ваши поля не содержат текста, потому что они не совпадают с теми, в которые ваш пользователь только что ввел текст.

Ответ №2:

Почему бы просто не полностью подклассировать AlertDialog.Builder и добавить метод для извлечения EditText значений?

Ответ №3:

Сделайте что-то вроде:

 View layout = inflater.inflate(R.layout.screen_dialog_login, null);

layout.findViewById(R.id.*yourwidget*);
  

я попробовал, и это помогло

Ответ №4:

Вот метод, который я использую:

 private void showPopUp3() {          

                 AlertDialog.Builder helpBuilder = new AlertDialog.Builder(AlarmReceiverActivity.this);
                 helpBuilder.setTitle("hi");
                // helpBuilder.setMessage(amp;quot;This is a Simple Pop Upamp;quot;);
                 final EditText input = new EditText(this);
                 input.setHeight(20);
                 input.setText("");
                 LayoutInflater inflater = getLayoutInflater();
                 final View checkboxLayout = inflater.inflate(R.layout.alarm, null);


                 checkboxLayout.findViewById(R.id.Yes).setOnClickListener(new OnClickListener(){
                        public void onClick(View arg0) {
                            // setTitle("button2");
                            checkboxLayout.findViewById(R.id.note).setVisibility(View.VISIBLE);
                        }
                    });
                 checkboxLayout.findViewById(R.id.No).setOnClickListener(new OnClickListener(){
                        public void onClick(View arg0) {
                            // setTitle("button2");
                            checkboxLayout.findViewById(R.id.note).setVisibility(View.INVISIBLE);
                        }
                    });
                 helpBuilder.setView(checkboxLayout);

                 helpBuilder.setPositiveButton("No",
                   new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                     // Do nothing but close the dialog
                         mMediaPlayer.stop();
                         finish();
                    }
                   });
                 helpBuilder.setNegativeButton("Yes",
                           new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                             // Do nothing but close the dialog
                     mMediaPlayer.stop();

                        //showSimplePopUp();

                            }
                           });
                 // Remember, create doesn't show the dialog
                 AlertDialog helpDialog = helpBuilder.create();
                 helpDialog.show();
            }