Is it possible to specify border in android button with keeping its background?

1.5k Views Asked by At

Is it possible to specify border in android button in its Activity? I want keep button png background and add specify border to that and remove it or change color of that dynamically.
A puzzle board consists of a few buttons in order to be selected, if the choice was incorrect to take red border.

1

There are 1 best solutions below

0
On BEST ANSWER

Use a ImageButton : use your png image as android:src and for background border add a drawable xml .

<ImageButton
    android:id="@+id/button"
    android:layout_width="75dp"
    android:layout_height="70dp"
    android:background="@drawable/border"
    android:padding="15dp"
    android:scaleType="fitCenter"
    android:src="@drawable/your_image" />

in res/drawable/border.xml

 <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/transparent" />
    <stroke
        android:width="3dp"
        android:color="@color/stroke_color"></stroke>
    <corners
        android:bottomLeftRadius="8dp"
        android:bottomRightRadius="8dp"
        android:topLeftRadius="8dp"
        android:topRightRadius="8dp" />
</shape>

To change the shape Border color programetically use:

ImageButton button = (ImageButton) findViewById(R.id.button);
GradientDrawable backgroundGradient = (GradientDrawable) button.getBackground();
backgroundGradient.setStroke(5, Color.RED);  // set stroke width and stroke color