Android Switch控件的使用
首先 效果图
如图所示
然后 布局内容
<Switch android:id="@+id/switch_istrue" android:layout_marginRight="15dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:thumb="@drawable/switch_ios_thumb" android:track="@drawable/switch_ios_track_selector" />
其中 布局有两个引用资源 @drawable/switch_ios_thumb 和 @drawable/switch_ios_track_selector
@drawable/switch_ios_thumb 资源内容为
可复制内容
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval"> <solid android:color="#FFF" /> <stroke android:width="3dp" android:color="#00000000" /> <size android:width="25dp" android:height="25dp" /> </shape>
@drawable/switch_ios_track_selector 资源布局为
可复制内容
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/switch_ios_track_on" android:state_checked="true" /> <item android:drawable="@drawable/switch_ios_track_off" android:state_checked="false" /> </selector>
@drawable/switch_ios_track_on 和 @drawable/switch_ios_track_off的内容分别是
以上就是Switch 控件的布局 最后就是控件的监听事件
public Switch aSwitch;
aSwitch =findViewById(R.id.switch_istrue);
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked){ //选中状态 可以做一些操作 }else { //未选中状态 可以做一些操作 } } });
除了监听之外 还可以直接设置Switch控件的状态
aSwitch.setChecked(true); //设置选中
aSwitch.setChecked(false); //设置取消