【问题标题】:How to get string-input from AlertDialogBox (EditText.xml)如何从 AlertDialogBox (EditText.xml) 获取字符串输入
【发布时间】:2017-09-22 16:45:42
【问题描述】:

这是我需要从AlertDialogEditText获取文本的方法

public void checkButton() {
    leggspillere = (Button) findViewById(R.id.leggspillere);       
    final LayoutInflater inflater = this.getLayoutInflater();       
    AlertDialog.Builder builder = new AlertDialog.Builder(this);   
    builder.setView(inflater.inflate(R.layout.create_user,null));              
    builder.setMessage("Lag en spiller");
    builder.setCancelable(true);
    builder.setPositiveButton("Ok",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {                
                // trying to get the EditText-string inside alertdialogbox input here.
                final String Name = UserName.                       
                Person person = new Person(Name, 0);                       
                dialog.dismiss();
                spillere.setText(person.getName() + " " + person.getScore());
            }
        }
    );
    //sette andre knappen "cancel"
    builder.setNegativeButton("no",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        }
    );
    AlertDialog alert = builder.create();
    alert.show();
}

XML:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:scaleType="center"
        android:background="#FFFFBB33"
        android:contentDescription="@string/app_name" />

    <EditText
        android:id="@+id/UserName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="16dp"
        android:inputType="textEmailAddress" />
</LinearLayout>

尝试从EditText.xml 获取输入/字符串以创建person 对象。 始终引用 null 对象。我找不到任何解决方案,请指点我。

【问题讨论】:

  • 是否将您的编辑文本溢出到您要设置文本的位置?
  • 那是一个TextView,我想直观地代表所有添加的玩家。
  • “这就是问题所在”不应以代码开头,而应以您实际遇到的实际口头技术问题开头。

标签: java android xml android-edittext android-alertdialog


【解决方案1】:

您如何尝试访问DialogInterface.OnClickListener 中的editText?

尝试在 View 对象中获取膨胀视图,并在该 View 对象变量上执行 findViewById。下面的代码应该可以正常工作:

LayoutInflater inflater = this.getLayoutInflater();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final View dialogView = inflater.inflate(R.layout.dialog_alert, null);
builder.setView(dialogView);
builder.setMessage("Lag en spiller");
builder.setCancelable(true);
builder.setPositiveButton("Ok",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                EditText editText = (EditText) dialogView.findViewById(R.id.d_alert_et);
                Log.v("tag", "Edit text value: " + editText.getText());
            }
        });
builder.setNegativeButton("no",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
AlertDialog alert = builder.create();
alert.show();

基本上是在一个View Object中得到膨胀的视图:

最终视图 dialogView = inflater.inflate(R.layout.dialog_alert, null);

然后在该视图对象上执行 findViewById:

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

editText.getText()

【讨论】:

    【解决方案2】:

    请。参考此代码:https://www.mkyong.com/android/android-custom-dialog-example/

    // custom dialog
    final Dialog dialog = new Dialog(context);
    dialog.setContentView(R.layout.custom);
    dialog.setTitle("Title...");
    
    // set the custom dialog components - text, image and button
    TextView text = (TextView) dialog.findViewById(R.id.text);
    text.setText("Android custom dialog example!");
    ImageView image = (ImageView) dialog.findViewById(R.id.image);
    **EditText edtName = (EditText) dialog.findViewById(R.id.edtName);**
    image.setImageResource(R.drawable.ic_launcher);
    
    Button dialogButton = (Button) 
    dialog.findViewById(R.id.dialogButtonOK);
    // if button is clicked, close the custom dialog
    dialogButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            **String s = edtName.getText().toString();**
            dialog.dismiss();
        }
    });
    
    dialog.show();
    }
    

    【讨论】:

      【解决方案3】:

      我更喜欢使用Material Dialog 库,因为它非常易于使用。

      您可以使用自定义视图或使用simple input

      1.我项目中的简单输入示例:

      new MaterialDialog.Builder(this)
          .title(R.string.input)
          .content(R.string.input_content)
          .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD)
          .input(R.string.input_hint, R.string.input_prefill, new MaterialDialog.InputCallback() {
              @Override
              public void onInput(MaterialDialog dialog, CharSequence input) {
                  // Do something
              }
          }).show();
      

      2.自定义视图示例:

              View view = LayoutInflater.from(context).inflate(R.layout.dialog_new_queue, null, false);
      
              MaterialDialog dialog = new MaterialDialog.Builder(context)
                      .customView(view, false).build();
              AutoCompleteTextView tv = view.findViewById(R.id.dialog_add_q_tv);
              Button btn = view.findViewById(R.id.dialog_add_queue_btn);
              btn.setOnClickListener(v -> {
                  String input = tv.getText().toString().trim();
                  Observable
                          .create(emitter -> {
                              if (input.isEmpty()) {
                                  emitter.onError(new IllegalArgumentException("اسم صف خالی است"));
                              } else if (dao.getQueue(pref.getLastUsername(), input) != null) {
                                  emitter.onError(new IllegalArgumentException("این اسم تکراری است!"));
                              } else {
                                  QueueModel q = new QueueModel(input, pref.getLastUsername(), System.currentTimeMillis());
                                  dao.insert(q);
                                  emitter.onComplete();
                              }
                          })
                          .subscribeOn(Schedulers.io())
                          .observeOn(AndroidSchedulers.mainThread())
                          .subscribe(o -> {},e ->{
                              tv.setError(e.getMessage());
                              tv.requestFocus();
                          },() -> {
                              Toast.makeText(context, "صف جدید ساخته شد", Toast.LENGTH_SHORT).show();
                              dialog.dismiss();
                              loadData();
                          });
              });
              dialog.show();
      

      【讨论】:

        【解决方案4】:

        替换两行:

        final String Name = UserName. 
        Person person = new Person(Name, 0); 
        

        EditText editText = (EditText) dialogView.findViewById(R.id.UserName);
        Person person = new Person(editText.getText(), 0); 
        

        【讨论】:

        • 嗯,应用程序不会崩溃,但 person 对象是 (null,0)。似乎仍然无法获得 EditText 输入。
        • 您输入的电子邮件地址有效吗?
        • 不只是纯文本。输入类型更改为“文本”。
        【解决方案5】:

        试试这个

        public void checkButton() {
        leggspillere = (Button) findViewById(R.id.leggspillere);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        
        LayoutInflater inflater = this.getLayoutInflater();
        
        builder.setView(inflater.inflate(R.layout.create_user, null));
        builder.setMessage("Lag en spiller");
        builder.setCancelable(true);
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                //Change here
                Dialog myDialog = (Dialog) dialog;
                EditText editText = (EditText) myDialog.findViewById(R.id.UserName);
                Person person = new Person(editText.getText(), 0); 
            }
        })
         //sette andre knappen "cancel"
        builder.setNegativeButton("no",  new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });      
         builder.create().show();
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多