How to take text input with DialogFragment in Android?

后端 未结 1 1121
忘掉有多难
忘掉有多难 2021-01-14 07:12

I am trying to get a value that user enters into a Dialog, using the recommended DialogFragment class for it, the Dialog constructs and runs fine, but I cannot return the va

相关标签:
1条回答
  • 2021-01-14 07:33

    There seems to be problem with the way you are referring to the edit text. You need to get it from the view you inflated Please try the below code which adds all functionality in your main activity itself. If you want you can adapt to your case with a separate class:

    public void showNoticeDialog() {
    
    public String inputvalue;
    
    LayoutInflater inflater = LayoutInflater.from(this);
    final View textenter = inflater.inflate(R.layout.dialog_add, null)
    final EditText userinput = (EditText) textenter.findViewById(R.id.item_added); 
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(textenter)
              .setTitle("Your title");
    builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
    
                   @override
                   public void onClick(DialogInterface dialog, int id) {        
                       inputvalue =  userinput.getText().toString();                  
                      // Do something with value in inputvalue
                   }
               })
               .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                     dialog.cancel();
    
                   }
               });      
        AlertDialog dialog = builder.create();
              builder.show();
             }
    

    For alert dialog , you need to inflate an xml, only if you are planning to have multiple views like more than 1 edittext in that dialog. If you plan to have only 1 edittext as in your example, you dont need an xml and you can directly define an edittext and set it as the view of the alert dialog.

    final EditText userinput = new EditText(context);
                builder.setView(userinput);
    
    0 讨论(0)
提交回复
热议问题