1、activity_main.xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="@+id/checkbox_warning"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="@drawable/checkbox_switch_selector"
android:button="@null"
android:text="switch开关"
android:layout_marginRight="90dp"
android:layout_marginLeft="70dp"
android:layout_marginTop="30dp"
android:textColor="#000000"
android:textSize="25dp"
android:focusable="false" />
</RelativeLayout>
主要用到背景选择器checkbox_switch_selector,以及去除复选框android:button="@null"
2、背景选择器checkbox_switch_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="true" android:drawable="@drawable/switch_on"/>
<item android:drawable="@drawable/switch_off"/>
</selector>
选择器中用到的两张图片:


3、MainActivity:
public class MainActivity extends AppCompatActivity {
private CheckBox checkbox_warning;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkbox_warning=(CheckBox)findViewById(R.id.checkbox_warning);
checkbox_warning.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(checkbox_warning.isChecked()){
}else{
}
}
});
}
}
4、效果预览:


网友评论