Input text dialog Android

365,726

Solution 1

Sounds like a good opportunity to use an AlertDialog.

As basic as it seems, Android does not have a built-in dialog to do this (as far as I know). Fortunately, it's just a little extra work on top of creating a standard AlertDialog. You simply need to create an EditText for the user to input data, and set it as the view of the AlertDialog. You can customize the type of input allowed using setInputType, if you need.

If you're able to use a member variable, you can simply set the variable to the value of the EditText, and it will persist after the dialog has dismissed. If you can't use a member variable, you may need to use a listener to send the string value to the right place. (I can edit and elaborate more if this is what you need).

Within your class:

private String m_Text = "";

Within the OnClickListener of your button (or in a function called from there):

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");

// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
builder.setView(input);

// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
    @Override
    public void onClick(DialogInterface dialog, int which) {
        m_Text = input.getText().toString();
    }
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }
});

builder.show();

Solution 2

I will add to @Aaron's answer with an approach that gives you the opportunity to style the dialog box in a better way. Here is an adjusted example:

AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Title");
// I'm using fragment here so I'm using getView() to provide ViewGroup
// but you can provide here any other instance of ViewGroup from your Fragment / Activity
View viewInflated = LayoutInflater.from(getContext()).inflate(R.layout.text_inpu_password, (ViewGroup) getView(), false);
// Set up the input
final EditText input = (EditText) viewInflated.findViewById(R.id.input);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
builder.setView(viewInflated);

// Set up the buttons
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
        m_Text = input.getText().toString();
    }   
}); 
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    }   
}); 

builder.show();

Here is the example layout used to create the EditText dialog:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="@dimen/content_padding_normal">

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <AutoCompleteTextView
            android:id="@+id/input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_password"
            android:imeOptions="actionDone"
            android:inputType="textPassword" />

    </android.support.design.widget.TextInputLayout>
</FrameLayout>

The final result:

EditText Dialog example

Solution 3

How about this EXAMPLE? It seems straightforward.

final EditText txtUrl = new EditText(this);

// Set the default text to a link of the Queen
txtUrl.setHint("http://www.librarising.com/astrology/celebs/images2/QR/queenelizabethii.jpg");

new AlertDialog.Builder(this)
  .setTitle("Moustachify Link")
  .setMessage("Paste in the link of an image to moustachify!")
  .setView(txtUrl)
  .setPositiveButton("Moustachify", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
      String url = txtUrl.getText().toString();
      moustachify(null, url);
    }
  })
  .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    }
  })
  .show(); 

Solution 4

If you want some space at left and right of input view, you can add some padding like

private fun showAlertWithTextInputLayout(context: Context) {
    val textInputLayout = TextInputLayout(context)
    textInputLayout.setPadding(
        resources.getDimensionPixelOffset(R.dimen.dp_19), // if you look at android alert_dialog.xml, you will see the message textview have margin 14dp and padding 5dp. This is the reason why I use 19 here
        0,
        resources.getDimensionPixelOffset(R.dimen.dp_19),
        0
    )
    val input = EditText(context)
    textInputLayout.hint = "Email"
    textInputLayout.addView(input)

    val alert = AlertDialog.Builder(context)
        .setTitle("Reset Password")
        .setView(textInputLayout)
        .setMessage("Please enter your email address")
        .setPositiveButton("Submit") { dialog, _ ->
            // do some thing with input.text
            dialog.cancel()
        }
        .setNegativeButton("Cancel") { dialog, _ ->
            dialog.cancel()
        }.create()

    alert.show()
}

dimens.xml

<dimen name="dp_19">19dp</dimen>

Hope it help

Solution 5

It's work for me

private void showForgotDialog(Context c) {
        final EditText taskEditText = new EditText(c);
        AlertDialog dialog = new AlertDialog.Builder(c)
                .setTitle("Forgot Password")
                .setMessage("Enter your mobile number?")
                .setView(taskEditText)
                .setPositiveButton("Reset", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String task = String.valueOf(taskEditText.getText());
                    }
                })
                .setNegativeButton("Cancel", null)
                .create();
        dialog.show();
    }

How to call? (Current activity name)

showForgotDialog(current_activity_name.this);

Share:
365,726
Luke Taylor
Author by

Luke Taylor

I'm a young fan of technology and innovation, passionate about robotics, programming, hacking, space and game development. Always up for an adventure!

Updated on August 20, 2022

Comments

  • Luke Taylor
    Luke Taylor over 1 year

    When a user clicks a Button in my App (which is printed in a SurfaceView), I'd like a text Dialog to appear and I would like to store the result in a String. I'd like the text Dialog to overlay the current screen. How can I do this?

  • Luke Taylor
    Luke Taylor almost 12 years
    The app seems to crash when I call "builder.show();". I get the following error message: "Can't create handler inside thread that has not called Looper.prepare();".
  • Luke Taylor
    Luke Taylor almost 12 years
    I've got a thread that constantly updates and renders a screen object, and I call the builder.show() method within the update method of the screen object.
  • Aaron
    Aaron almost 12 years
    Oh. If you're on a worker thread, try putting the builder.show(); call with runOnUiThread, similar to this example: stackoverflow.com/a/3134720/1098302 Or maybe it would be better to put all the code above (that creates the AlertDialog) in a separate method, and call that method from within runOnUiThread.
  • Admin
    Admin over 10 years
    Thank you. Thats good. Howerver, there's a little problem. Need to declare global Context, Context cont; and then, replace "this" in alertdialog by cont. AlertDialog.Builder builder = new AlertDialog.Builder(cont); final EditText input = new EditText(cont);
  • kunal18
    kunal18 over 9 years
    I think instead of creating a global variable for context, you can pass the context like: "MainActivity.this" (you need to replace the text "MainActivity" with activity class name you want to use).
  • Ruchir Baronia
    Ruchir Baronia about 8 years
    How do I add a check box with text next to it under the edit text? Thanks so much Aaron
  • Atul
    Atul almost 8 years
    Superb solution! I just replaced getView() with findViewById(android.R.id.content)and it all worked like charm. Thanks a lot for sharing :)
  • ewall
    ewall almost 8 years
    Might be worth noting that, like most Android UI, this is all asynchronous... meaning it won't wait for the user to tap OK unless you have something making that the gate to the next step...
  • SMBiggs
    SMBiggs over 7 years
    @user2891317: if this is within a View's scope instead of an Activity's or a Fragment's, you can use getContext() for the new EditText.
  • SMBiggs
    SMBiggs over 7 years
    Pretty much the same as Aaron's, but chains the builder. Matter of personal preference as both work fine.
  • Martin Erlic
    Martin Erlic over 7 years
    Remember to cast that findViewById with (ViewGroup)!
  • Tobias Reich
    Tobias Reich over 7 years
    If you call the Inflater with the last argument false, why using the second parameter? If I understand if right, this is only used if set to true.
  • RichArt
    RichArt about 7 years
    How can I delimit the width of the alert dialog? I tried with input.setMaxWidth(100); but it doesn't work.
  • Aaron
    Aaron about 7 years
    @RichArt The size seems to be controlled by the AlertDialog, rather than the view you choose to set to it (input). Maybe the first option in this answer would help?
  • Jaroslav Záruba
    Jaroslav Záruba about 7 years
    "Element AutoCompleteTextView is not allowed here..."
  • Atul
    Atul almost 7 years
    @JPerk: android.R.id.content gives you the root element of a view. Refer this please: stackoverflow.com/a/12887919/1911652
  • Meet Vora
    Meet Vora over 6 years
    what about input.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE). How can I use multi-line. I tried setting this flag, but it remains single line.
  • waseefakhtar
    waseefakhtar over 6 years
    Works brilliantly! Thanks for this.
  • slott
    slott over 6 years
    Really good idea to use the TextInputLayout to make it shine even more
  • Babken Vardanyan
    Babken Vardanyan about 6 years
    I am getting this error: You need to use a Theme.AppCompat theme (or descendant) with the design library.. Any idea?
  • CarlosMacMar
    CarlosMacMar about 6 years
    @BabkenVardanyan I solved it changing AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); with AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(MainActivity.this‌​);
  • Edric
    Edric over 5 years
    Just wondering, but what's the value of @dimen/content_padding_normal?
  • Studio2bDesigns
    Studio2bDesigns over 5 years
    Just curious why the (-1) downvote? The logic I provided works exactly as intended and as described.. I felt it was a good addition to this post that hadn't been mentioned yet, and is a perfectly sound alternative solution. However, if you have a legitimate reason for downvoting the information I provided, it would be slightly more helpful if you could please provide some context for why you did, so myself and others can learn and understand the reasoning.. Downvotes can actually be very useful and helpful in the learning process - but only when there is context behind why.
  • A moskal escaping from Russia
    A moskal escaping from Russia over 4 years
    What's resources?
  • Sam Chen
    Sam Chen about 4 years
    Want to point out one thing, inflate(R.layout.xxx, (ViewGroup) getView(), false) and inflate(R.layout.xxx, findViewById(android.R.id.content, false) and inflate(R.layout.xxx, null), they all have same effect, I have tested. I suggest adding 16dp horizontal padding and 8dp top padding to the xxx layout.