美文网首页
最简单的switch开关(CheckBox)实现

最简单的switch开关(CheckBox)实现

作者: 467443babd7d | 来源:发表于2018-05-05 21:56 被阅读0次

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>
选择器中用到的两张图片:


switch_off.png switch_on.png

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、效果预览:


Screenshot_1525528539.png Screenshot_1525528545.png

相关文章

网友评论

      本文标题:最简单的switch开关(CheckBox)实现

      本文链接:https://www.haomeiwen.com/subject/bsoerftx.html