How to add an Icon to a Button in Android from Java?

Viewed 1033

I want to add an icon to a Button that I created from Java, after hours I didn't find a solution yet...

I have something like this:

Button button = new Button(context);

And I'd like to have something like this:

button.setIcon(Icon myicon);

Is this possible? ;)

3 Answers

You can use the MaterialButton:

MaterialButton button = new MaterialButton(this);
button.setIcon(ContextCompat.getDrawable(this,R.drawable.ic_add_24px));
button.setText("Button");

enter image description here

If you want a Button with image then in XML you have ImageButton that have attribute of drawableLeft/drawableRight..etc. So you can set in from there. In java I think you can set in the same way by calling setResourceDrawable.

you could also setIcon an XML file, Please try this

 <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Click Me"
    android:drawableRight="@drawable/ic_icon" <!--also have drawableLeft:-->
    android:drawablePadding="20dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
Related