SwitchCompat 控件本身含有属性
textOn:控件打开时显示的文字
textOff:控件关闭时显示的文字
thumb:控件开关的图片
track:控件开关的轨迹图片
typeface:设置字体类型
switchMinWidth:开关最小宽度
switchPadding:设置开关 与文字的空白距离
switchTextAppearance:设置文本的风格
checked:设置初始选中状态
splitTrack:是否设置一个间隙,让滑块与底部图片分隔(API 21及以上)
showText:设置是否显示开关上的文字(API 21及以上)
这个控件分为xml配置和java代码控制
其中xml配置很简单:
<android.support.v7.widget.SwitchCompat
android:id="@+id/switch_kt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:switchMinWidth="20dp"
android:textOn="on"
style="@style/MySwitchTheme"
app:showText="true"
android:textOff="off" />
对应的style配置
<style name="MySwitchTheme">
<item name="colorControlActivated">#EF8A33</item>
<item name="colorSwitchThumbNormal">#FFF1F1F1</item>
<item name="android:colorForeground">#FF2F2F2F</item>
</style>
这样显示出来的 文字颜色默认是黑色,按钮未选中是白色,选中后颜色的橘黄色。也就是 第二个属性。具体属性意思请百度。
如果要设置text字体颜色,在style文件中添加对应属性
<style name="texton" parent="Theme.AppCompat.Light">
<item name="android:textColor">#ffffff</item>
<item name="android:textSize">12sp</item>
</style>
第一个是字体颜色,第二个是字体大小
app:switchTextAppearance="@style/texton"
在上面控件中添加这个属性,就可以了————》但是这个属性是单一的text字体颜色,就是从始至终都是白色或者你写的那个颜色,如何让选中不同状态时候显示不同颜色呢。 简单 java代码控制
这里要用到的属性是:switchTextAppearance()
style代码:
<style name="textoff" parent="Theme.AppCompat.Light">
<item name="android:textColor">#000000</item>
<item name="android:textSize">12sp</item>
</style>
<style name="texton" parent="Theme.AppCompat.Light">
<item name="android:textColor">#ffffff</item>
<item name="android:textSize">12sp</item>
</style>
具体代码:
public class MainActivity extends AppCompatActivity {
private SwitchCompat switchCompat;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchCompat=findViewById(R.id.s_v);
//如果在xml控件中未写这个属性,可以在这里写,如何写了可以不用写
switchCompat.setChecked(false);
switchCompat.setSwitchTextAppearance(this,R.style.textoff);
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
switchCompat.setSwitchTextAppearance(
MainActivity.this,R.style.texton);
}else {
switchCompat.setSwitchTextAppearance(MainActivity.this,R.style.textoff);
}
}
});
}
}
到此结束