嗨我做了一個自定義的圓角按鈕(gps_button),它的作品,但我想改變按鈕的顏色取決於它的狀態條件,但顏色不變。顏色變量存儲在Colors.xml中更改顏色或自定義按鈕
我的主要問題是如何將Color.xml中的顏色設置爲我的自定義按鈕?
這是我的代碼主要活動:
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();
}
}
這是自定義按鈕:
<?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>
這是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>
感謝,但對於「工廠」按鈕看起來適用,它會爲我custome按鈕工作>? – Cardona
是的。只需使用gps_button.setBackgroundColor(getResources()。getColor(R.color.colorPrimary)); –
@Cardona所有按鈕,包括您的自定義按鈕,都可以訪問相同的setBackgroundColor()方法 –