How to programmatically set drawableLeft on Android button?
You can use the setCompoundDrawables
method to do this. See the example here. I used this without using the setBounds
and it worked. You can try either way.
UPDATE: Copying the code here incase the link goes down
Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);img.setBounds(0, 0, 60, 60);txtVw.setCompoundDrawables(img, null, null, null);
or
Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);txtVw.setCompoundDrawablesWithIntrinsicBounds(img, null, null, null);
or
txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);
Simply you can try this also
txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);
• Kotlin Version
Use below snippet to add a drawable left to the button:
val drawable = ContextCompat.getDrawable(context, R.drawable.ic_favorite_white_16dp)button.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)
.
• Important Point in Using Android Vector Drawable
When you are using an android vector drawable and want to have backward compatibility for API below 21, add the following codes to:
In app level build.gradle
:
android { defaultConfig { vectorDrawables.useSupportLibrary = true }}
In Application class:
class MyApplication : Application() { override fun onCreate() { super.onCreate() AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) }}