Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

Android - Custom Dialog - Can't get text from EditText

I have a problem with a custom dialog.
My dialog consists of a TextView, EditText and an "Ok" Button. After clicking "Ok", it should get the text from EditText field and assign it to the String variable "name" defined in the Activity.
Everything seems to work, no errors etc, however "text" is always an empty String.
I read some topics about such problems, however I'm not really sure what adjustments I should make here.
I'm quite new to Android programming, so I'd be grateful if somebody could explain the problem to me. Thanks in advance.

     final Dialog dialog = new Dialog(MyActivity.this);
     dialog.setContentView(R.layout.custom_dialog);
     dialog.setTitle("Title");

     final View layout = View.inflate(this, R.layout.custom_dialog, null);
     Button button = (Button) dialog.findViewById(R.id.dialog_ok);
     button.setOnClickListener(new OnClickListener() {
         public void onClick(View v) {
                EditText edit=(EditText)layout.findViewById(R.id.dialog_edit);
                String text=edit.getText().toString();

                name=text;

                dialog.dismiss();
         }
     });   

     dialog.show();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to inflate a xml file into dialog box for creating custom version you can use the following code which gets two input from user

LayoutInflater linf = LayoutInflater.from(this);            
final View inflator = linf.inflate(R.layout.twoinputs, null);
AlertDialog.Builder alert = new AlertDialog.Builder(this); 

alert.setTitle("Tilte"); 
alert.setMessage("Message"); 
alert.setView(inflator); 

final EditText et1 = (EditText) inflator.findViewById(R.id.editText1);
final EditText et2 = (EditText) inflator.findViewById(R.id.editText2);

alert.setPositiveButton("ok", new DialogInterface.OnClickListener() { 
   public void onClick(DialogInterface dialog, int whichButton) 
   { 
          String s1=et1.getText().toString();
          String s2=et2.getText().toString();
          //do operations using s1 and s2 here...
   } 
}); 

alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
   public void onClick(DialogInterface dialog, int whichButton) { 
            dialog.cancel(); 
   } 
}); 

alert.show(); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...