0

I'm trying to make a button in Android that has a border but with a different background tint when it is pressed, and the ability to change the color of the button background. I know adding a border is assigning it a shape and that tap states are through a selector with different items, but the problem is that the button background color is meant to be user configured.

Without tap states, I am able to allow the user to change the background color of my shape by just doing:

GradientDrawable bgShape = (GradientDrawable) btn.getBackground();
        //color value is obtained from shared preferences
        if (sharedPref.contains(pref_color)) {
            String color = sharedPref.getString(pref_color, "");
            bgShape.setColor(Color.parseColor(color));
        }

But I can't do the first line if my button is going to be assigned a selector. I don't know how I would get the reference to the drawable shape.

For reference, my button border shape is:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">

    <stroke android:width="5px" android:color="#ffffff" />
</shape>

The selector would look like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/button_press" android:state_pressed="true"/>
<item android:drawable="@drawable/button_border" />

</selector>

Is there a way to accomplish this?

Community
  • 1
  • 1
Jason
  • 445
  • 1
  • 6
  • 16

1 Answers1

1

you can define an id for drawable layer and then change their properties in runtime

LayerDrawable drawSettings = (LayerDrawable)
getResources().getDrawable(R.drawable.sample);
GradientDrawable backSettings = (GradientDrawable)
drawSettings.findDrawableByLayerId(R.id.backtemp);

and after change color reset it to button background

view.setBackground(drawable);

this is a sample drawable sample.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/backtemp">
<shape
android:shape="oval" >
<solid android:color="@color/default_color"/>
</shape>
</item>

<item
android:drawable="@drawable/w_pref">
</item>
</layer-list>
Elias Fazel
  • 2,093
  • 16
  • 20