4

I am trying to make something like this example:

Screenshot of a user name text field with a check suffix icon

I want the drawable to show when I verify the user name from the server.

I am using Material Design Text Input Field & EditText. Yes, I can do it with a simple EditText and an ImageView, but I want to use the standard elements.

I have looked at the official documentation, there is a way to add the image at the Right corner using XML, but I want to add it programmatically.

Edric
  • 24,639
  • 13
  • 81
  • 91
Hasnain Ghias
  • 69
  • 1
  • 12

2 Answers2

16

Use the setEndIconDrawable method:

    textInputLayout.setEndIconDrawable(R.drawable.xxxx);
    textInputLayout.setEndIconMode(TextInputLayout.END_ICON_CUSTOM);

or in a layout:

  <com.google.android.material.textfield.TextInputLayout
        app:endIconDrawable="@drawable/xxxxx"
        app:endIconMode="custom"

enter image description here

More info in the official doc.

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
3

You need to to set your drawable programmatically like below

inputTextEditText.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(context,R.drawable.drawableRight), null)
Mehul Kabaria
  • 6,404
  • 4
  • 25
  • 50
  • Thanks, the drawable is added but now the text is overlapping the left icon. Here is the screenshot : https://ibb.co/5j5N5nZ – Hasnain Ghias Jun 25 '20 at 11:24
  • for that may you need to add padding start on it. – Mehul Kabaria Jun 25 '20 at 11:53
  • Thanks for the help, I fixed it with "setCompoundDrawablesRelativeWithIntrinsicBounds" – Hasnain Ghias Jun 25 '20 at 12:04
  • @MehulKabaria It is not correct. Using the `setCompoundDrawablesWithIntrinsicBounds` on the `TextInputEditText` != to use `app:endIconDrawable` (official way) in the layout. Check also the official doc: **Note:** You should opt to use the `EndIconMode` API instead of setting an end/right compound `Drawable` on the `TextInputEditText` – Gabriele Mariotti Jun 25 '20 at 13:22