简体   繁体   中英

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

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

You can use the MaterialButton :

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

在此处输入图像描述

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM