一手遮天 Android - view(选择类): Switch 基础

项目地址 https://github.com/webabcd/AndroidDemo
作者 webabcd

一手遮天 Android - view(选择类): Switch 基础

示例如下:

/view/selection/SwitchDemo1.java

/**
 * Switch - 状态切换控件
 *     setChecked(boolean checked) - 设置当前控件的选中状态
 *     isChecked() - 获取当前控件的选中状态
 *     setOnCheckedChangeListener(OnCheckedChangeListener listener) - 状态切换控件的选中状态发生变化时的回调
 */

package com.webabcd.androiddemo.view.selection;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;

import com.webabcd.androiddemo.R;

public class SwitchDemo1 extends AppCompatActivity {

    private Switch _switch1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_selection_switchdemo1);

        _switch1 = (Switch)findViewById(R.id.switch1);

        sample();
    }

    private void sample() {
        _switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Toast.makeText(SwitchDemo1.this, String.valueOf(isChecked), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

/layout/activity_view_selection_switchdemo1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!--
        Switch - 状态切换控件
            checked - 选中状态
    -->
    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true" />

    <!--
        Switch - 状态切换控件
            switchMinWidth - 控件的宽度
            showText - 是否需要显示 textOff 和 textOn 指定的文本
            textOn - 选中状态时,thumb 上显示的文本
            textOff - 未选中状态时,thumb 上显示的文本
    -->
    <Switch
        android:id="@+id/switch2"
        android:layout_marginTop="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:switchMinWidth="200dp"
        android:showText="true"
        android:textOff="关"
        android:textOn="开" />

</LinearLayout>


项目地址 https://github.com/webabcd/AndroidDemo
作者 webabcd

posted @ 2021-05-31 13:05  webabcd  阅读(82)  评论(0编辑  收藏  举报