开关按钮ToggleButton

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhou906767220/article/details/80499494

ToggleButton继承关系

这里写图片描述

相关属性

  • android:disabledAlpha:设置按钮在禁用时的透明度
  • android:textOff:按钮没有被选中时显示的文字
  • android:textOn:按钮被选中时显示的文字

方法

返回值 方法 解释
CharSequence getAccessibilityClassName() 获得类的名称
CharSequence getTextOff() 获得开关未选中时的文本
CharSequence getTextOn() 获得开关选中时的文本
void setBackgroundDrawable(Drawable d) 设置按钮的背景
void setChecked(boolean checked) 更改按钮选中是的状态
void setTextOff(CharSequence textOff) 设置开关未选中时的文本
void setTextOn(CharSequence textOn) 设置开关选中时的文本

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"
    android:gravity="center_horizontal">

   <ToggleButton
       android:id="@+id/toggle_button"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:textOff="开"
       android:textOn="关" />

</LinearLayout>

java 文件

package com.siomt.togglebuttondemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {
    ToggleButton toggleButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toggleButton = findViewById(R.id.toggle_button);
        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    toggleButton.setTextOff("开");
                }else {
                    toggleButton.setTextOn("关");
                }
            }
        });
    }
}

Demo 地址 https://github.com/Siomt/BlogSample

猜你喜欢

转载自blog.csdn.net/zhou906767220/article/details/80499494
今日推荐