Android setCompoundDrawablePadding not working

Viewed 1493

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));
1 Answers

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);
    }
}
Related