0

Hi I made a custom round corner button ( gps_button ) which works but I would like to change the color of the button depending on it's state condition but, the color is not changing. Color variables are stored in Colors.xml

My main question is how to set the color from Color.xml to my custom button ?

this is my code Main Activity:

public void start_gps (View view){

gps_button = (Button) (findViewById(R.id.start_gps_button));

if ((log_state == true) && (start_gps_button_state == false)){

            start_gps_button_state = true;
            gps_button.setBackgroundColor(R.color.startGpsColor);
            gps_button.setText("STOP");
            voyagePoints.setText("0");

            Toast.makeText(this, "GPS Started", Toast.LENGTH_SHORT).show();

        }else if ((log_state == true) && start_gps_button_state == true){

            start_gps_button_state = false;
            gps_button.setBackgroundColor(R.color.stopGpsColor);
            gps_button.setText("START");

            Toast.makeText(this, "GPS Stopped", Toast.LENGTH_SHORT).show();
        }
    }

This is the custom button:

    <?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" >
        <shape android:shape="rectangle"  >
            <corners android:radius="10dip" />
            <stroke android:width="1dip" android:color="#1EB7F1" />
            <gradient android:angle="-90" android:startColor="#1EB7F1" android:endColor="#1EB7F1"  />
        </shape>
    </item>
    <item android:state_focused="true">
        <shape android:shape="rectangle"  >
            <corners android:radius="10dip" />
            <stroke android:width="1dip" android:color="#1EB7F1" />
            <solid android:color="#1EB7F1"/>
        </shape>
    </item>
    <item >
        <shape android:shape="rectangle"  >
            <corners android:radius="10dip" />
            <stroke android:width="1dip" android:color="#1EB7F1" />
            <gradient android:angle="-90" android:startColor="#1EB7F1" android:endColor="#1EB7F1" />
        </shape>
    </item>
</selector>

This is the Color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#A7E483</color>
    <color name="colorPrimaryDark">#A7E483</color>
    <color name="colorAccent">#FF4081</color>
    <color name="stopGpsColor">#F9108E</color>
    <color name="startGpsColor">#1EB7F1</color>
</resources>
Cardona
  • 17
  • 5

2 Answers2

0

See this question. You have to use button.setBackgroundColor(getResources().getColor(R.color.colorPrimary));

MacLean Sochor
  • 435
  • 5
  • 14
0

I got it to work, found it also from here https://stackoverflow.com/a/34057311/1515105

gps_button.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.startGpsColor)));
Cardona
  • 17
  • 5