Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android custom buttons

I am creating custom buttons in android but want to avoid repetition.

I'm trying to create 2 togglable buttons which share the same design but a different image icon instead of text.

Currently I have this:

enter image description here

And i'm using this xml as a drawable resource:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <item>
        <shape>
            <padding
                android:bottom="5dp"
                android:left="5dp"
                android:right="5dp"
                android:top="5dp" />
            <corners android:radius="20dp"/>
        </shape>
    </item>

    <item>
        <shape>
            <padding
                android:bottom="5dp"
                android:left="-5dp"
                android:right="5dp"
                android:top="-5dp" />

            <solid android:color="#edebeb"></solid>

            <corners android:radius="20dp"/>
        </shape>
    </item>
    <item>
        <shape>
            <size android:height="150dp" android:width="150dp"></size>
            <padding
                android:bottom="5dp"
                android:left="-5dp"
                android:right="5dp"
                android:top="-5dp" />

            <solid android:color="#fff"></solid>

            <corners android:radius="20dp"/>
        </shape>
    </item>

</layer-list>

How can I display a different image in the center of each button without duplicating the xml file?

Is there any way I can pass a value to each button in the .java file of my activity so that i can use it to show a different image for each button?

like image 448
Bogdan Avatar asked Nov 09 '22 07:11

Bogdan


1 Answers

If you use an ImageView then you can set the icon as src and still use your drawable as the background:

 <ImageView ...
    android:src="@drawable/ic_whatever"
    android:background="@drawable/background" />

All views support onClick so it can still act as a button. Alternatively you can nest drawables so you can have the following for each different button style:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <item android:drawable="@drawable/ic_whatever" />
    <item android:drawable="@drawable/background" />
</layer-list>

The java version of what I suggested above (from an Activity):

public void onCreate(...) {
    ...
    ((ImageView) findViewById(R.id.my_button)).setImageResource(R.drawable.ic_whatver);
}
like image 190
Nick Cardoso Avatar answered Nov 15 '22 11:11

Nick Cardoso