Android开发 第五课 控件ToggleButton

来源:互联网 发布:比赛倒计时软件 编辑:程序博客网 时间:2024/05/18 00:26

1.ToggleButton有两种状态:选中和未选中状态
并且需要不同的状态设置 不同的显示文本
toggle /ˈtɒɡəl/ n. 开关,触发器;拴扣;[船] 套索钉(疼够)
2.属性
android:checked=”true” 代表当前按钮是否选中
android:textOff=”关” 若checked=”false”则textOff
android:textOn=”开” 若checked=”true”则textOn

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.adb.li806.demo3.MainActivity"    android:orientation="vertical"><!--  textOn:true      textOff;false -->    <ToggleButton        android:checked="false"        android:id="@+id/toggleButton1"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:textOn="哆啦A梦 开心"        android:textOff="哆啦A梦 流泪"        android:textSize="20sp"        />    <ImageView        android:id="@+id/imageView"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:background="@drawable/doraemonsad"/></LinearLayout>
package com.adb.li806.demo3;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;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.toggleButton1);        img = (ImageView) findViewById(R.id.imageView);        /*        *给当前的tb(ToggleButton)设置监听器        * 监听器的实现方法:接口        **/        tb.setOnCheckedChangeListener(this);        //接口来源import android.widget.CompoundButton.OnCheckedChangeListener    }    @Override    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {        /*        * 当tb被点击的时候,当前的方法会执行。        * CompoundButton buttonView 检测哪个tb被点击(代表被点击控件的本身)        * boolean isChecked 当前tb的状态是off还是on(代表被点击的控件的状态)        *        * 当点击这个tb的时候,跟换img的背景        * isChecked? R.drawable.doraemonsad : R.drawable.doraemonhappy        * 一个三目运算        * 判断tb的状态true 选 doraemonsad false选doraemonhappy        * */        img.setBackgroundResource(isChecked? R.drawable.doraemonsad : R.drawable.doraemonhappy);    }}

这里写图片描述
这里写图片描述

原创粉丝点击