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

2

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.