How to take text input with DialogFragment in Android?

南楼画角 提交于 2019-12-01 10:40:26

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!