Android 开关控件Switch的简单使用

来源:互联网 发布:淘宝主页图片大全 编辑:程序博客网 时间:2024/04/28 18:28

    在很多app的设置页面,或者是一些功能的开关界面,我们常常用到 Switch(开关) 来展示状态,今天说说新学到的Switch控件。

    最基本情况的按钮:

   <Switch        android:id="@+id/switch_普通开关"        android:layout_width="match_parent"        android:layout_height="wrap_content" />
    效果如图:


    简单设置:

<pre name="code" class="html">   <Switch        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:textOff=""        android:textOn=""        android:switchMinWidth="120dp"        android:thumb="@android:color/transparent"        android:track="@drawable/switch_track"        />

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item android:drawable="@drawable/switch_close" android:state_checked="false" />    <item android:drawable="@drawable/switch_open" android:state_checked="true" /></selector>

    效果展示:


    这里layout_width:这能设置整个布局的宽度,不能设置具体的Switch的大小,需要使用switchMinWidth属性来设置。

    thumb:文字所携带的背景,设置为背景色进行隐藏。不设置会出现一个背景框。

    track:设置开关的背景图片,类似于button的background。

    textoff、texton:设置开关时的文字显示。

    最后说说Switch的点击事件:

    private Switch mSwitch;    private TextView mText;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mSwitch = (Switch) findViewById(R.id.switch_);        mText = (TextView) findViewById(R.id.text_);        // 添加监听        mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {            @Override            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {                if (isChecked){                    mText.setText("开启");                }else {                    mText.setText("关闭");                }            }        });    }

    如图所示,没什么可以说的。。







0 0
原创粉丝点击