Wednesday, September 28, 2011

Android Dialog Input Text

Moving ahead from custom dialog example and other dialog example, here we are going to see about how to get input text from user in dialog using edittext.
In some cases we may need to get input from user in dialog. At that time we need no to use custom dialog instead of that you can use simple alert dialog itself by using setView(View view) property. Using setView() we can set any view to alert. Here we set the edittext view to setView() to get input from user.

public class DialogWithInputBox extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final AlertDialog.Builder alert = new AlertDialog.Builder(this);
        final EditText input = new EditText(this);
        alert.setView(input);
        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                String value = input.getText().toString().trim();
                Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT)
.show();
            }
        });

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

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.