4

I have a TextInputEditText in my layout to which I need to add a drawable end. Drawable end is appearing but I am not able to add drawable padding end to it.

Below is the piece of code which I tried:

  editText.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.error), null);
  editText.setCompoundDrawablePadding(getResources().getDimensionPixelSize(R.dimen.image_padding));
Anju
  • 9,379
  • 14
  • 55
  • 94
  • Don't use null. Use 0 in place of null. – Sanwal Singh Oct 30 '18 at 10:21
  • @Shane This also doesn't work. – Anju Oct 30 '18 at 12:02
  • 1
    Your code looks correct. What type of drawable are you using? What are you expecting to see when you increase the padding? The drawable should stay at the same position, only the available space for the text will shrink. – Maik Oct 31 '18 at 05:50
  • @maik Its a normal error image. The ! one – Anju Oct 31 '18 at 08:21
  • 2
    Could you please provide us the whole XML layout? TextInputEditText may not have enough space to expand horizontally. Could you please also debug what `getResources().getDimensionPixelSize(R.dimen.image_padding)`returns? – Egemen Hamutçu Nov 07 '18 at 11:23
  • Are you expecting the compound drawable padding to move the icon away from the edge of the edit text? Or are you expecting it to increase the spacing between the icon and the text contents? – Ben P. Nov 09 '18 at 18:54
  • Don't forget something important: you are applying the compound drawable to your `TextInputEditText`. This view, most commonly, will be encapsulation in a `TextInputLayout`. Which means that the padding will not be applied to the line above the edit text. Here is an example of a [testing app](https://duaw26jehqd4r.cloudfront.net/items/173i1J1n3a1H1o2i1y37/%5Bd86aedac5a845a5b2a0e6def097b8a18%5D_Image+2018-11-10+at+4.19.04+PM.png?v=5d5ad2dd) that I made. – André Sousa Nov 10 '18 at 16:21

1 Answers1

3

As getResources().getDrawable is deprecated, it's better to use ContextCompat.getDrawable() instead. If the drawablePadding is not change and it's not necessary to handle it programmatically, try to set it in xml file.

editText.setCompoundDrawablesWithIntrinsicBounds(
    null, 
    null, 
    ContextCompat.getDrawable(context, R.drawable.error), 
    null
);

In layout xml:

<android.support.design.widget.TextInputEditText
    android:id="@+id/editText"
    ...
    android:drawablePadding="@dimen/image_padding"
/>

.

If you are using an android vector drawable and want to have backward compatibility for API below 21, add the following snippets.

In app level build.gradle:

android {
    defaultConfig {
        vectorDrawables.useSupportLibrary = true
    }
}

In Application class:

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
    }
}
aminography
  • 21,986
  • 13
  • 70
  • 74