Android source code to show a popup dialog with a text field

I am working on a way to rapidly mock up Android applications using Android Studio, i.e., to rapidly prototype Android applications on the fly, and little snippets of code help to make this happen. For instance, this snippet of code shows how to show a popup dialog to prompt a user to enter information into a text field:

private void showAddItemDialog(Context c) {
    final EditText taskEditText = new EditText(c);
    AlertDialog dialog = new AlertDialog.Builder(c)
        .setTitle("Add a new task")
        .setMessage("What do you want to do next?")
        .setView(taskEditText)
        .setPositiveButton("Add", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String task = String.valueOf(taskEditText.getText());
            }
        })
        .setNegativeButton("Cancel", null)
        .create();
    dialog.show();
}

(The body of that method comes from this sitepoint.com example.)

I call that method when an Android FloatingActionButton (Fab) is tapped, like this:

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        showAddItemDialog(MainActivity.this);
    }
});

That code results in an Android popup dialog that looks like this:

An Android popup dialog with a text field

That may not seem like much, but when you add up a few dozen little tips like this, you can rapidly prototype Android applications in Android Studio very rapidly.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.