如何在Android Studio(Java)中创建一个切换按钮,当状态为ON时改变其轨迹/拇指颜色(例如,黑色处于ON状态,红色处于OFF状态)。
我已经尝试访问tack.xml
或color.xml
中的颜色,但每次打开/关闭按钮时都不知道如何更改它们,特别是切换轨道的背景颜色(我已经能够改变整个Btn的背景)。你知道我怎么能改变Switch轨道的背景颜色吗?
以下是我的代码MainActivity
的重要部分:
private TextView switchState;
private Switch mySwitch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchState = (TextView) findViewById(R.id.switchState);
mySwitch = (Switch) findViewById(R.id.mySwitch);
track = (trackColor) findViewById(R.id.trackColor); //**!!
// set the Switch to off
mySwitch.setChecked(false);
//now you need a listener to check changes in state
mySwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
switchState.setText("Switch is ON!");
mySwitch.setBackgroundColor(Color.RED);
trackColor.setBackgroundColor(Color.RED); //**!!
} else {
switchState.setText("Switch is OFF!");
}
}
});
}
(!!)它无法解析符号轨道和trackColor,我无法解释原因。
track.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<size android:height="40dp" />
<gradient
android:id="@+id/trackColor"/>
<gradient
android:height="40dp"
android:startColor="#2979FF"
android:endColor="#FFFF00"/>
</shape>
activity_main.xml中
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.nick.Simple_Flashlight.MainActivity"
android:background="@drawable/radial_background"
>
<Switch
android:id="@+id/mySwitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:switchMinWidth="200dp"
android:rotation="270"
android:thumb="@drawable/highlight_black_96x96"
android:track="@drawable/track" />
</RelativeLayout>