Android控件ToggleButton多状态按钮 Android控件ToggleButton多状态按钮使用详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Android控件ToggleButton多状态按钮 Android控件ToggleButton多状态按钮使用详解

朱卫东   2021-03-24 我要评论
想了解Android控件ToggleButton多状态按钮使用详解的相关内容吗,朱卫东在本文为您仔细讲解Android控件ToggleButton多状态按钮的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Android,ToggleButton,多状态按钮,下面大家一起来学习吧。

什么是ToggleButton?

ToggleButton一般有两种状态:选中和未选中
并且需要为不同状态设置不同的文本

ToggleButton属性

android:checked=”true”——当前按钮状态,选中为”true”,未选中为”false”
android:textOn=”开”
android:checked=”true”的时候,显示 取决于checked的状态,即当checked=”true”的时候,显示textOn=”开”,当checked=”false”的时候,显示checked=”true”

先来看一下实现效果:

具体代码

 <ToggleButton
 android:checked="false"
 android:id="@+id/toggleButton"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:textOn="开"
 android:textOff="关" />
 <ImageView
 android:id="@+id/imageView1"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:src="@drawable/off" />
package com.example.admin.demo;

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

public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {

 private ToggleButton tb;
 private ImageView img;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 // 初始化控件
 tb = (ToggleButton) findViewById(R.id.toggleButton);
 img = (ImageView) findViewById(R.id.imageView1);

 //设置监听器
 tb.setOnCheckedChangeListener(this);
 }

 @Override
 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
 img.setImageResource(isChecked?R.drawable.on:R.drawable.off);
 }
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们