4

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? ;)

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
Bat BRT
  • 47
  • 2
  • 6
  • Does this answer your question? [How to programmatically set drawableLeft on Android button?](https://stackoverflow.com/questions/4502605/how-to-programmatically-set-drawableleft-on-android-button) – javdromero May 02 '21 at 17:21
  • Yes maybe, i'll try it! thank you – Bat BRT May 02 '21 at 17:47

3 Answers3

3

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

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
  • 1
    Thank you very much! That's exactly what I was searching for! In fact I'm new to Android Studio and java, so I don't know all those classes of widgets yet... I should learn them ;) – Bat BRT May 03 '21 at 13:52
0

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.

Mohit Kumar
  • 41
  • 1
  • 7
0

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" />
Ganesh MB
  • 1,109
  • 2
  • 14
  • 27