ToggleButton控件

来源:互联网 发布:往复式 旋转式 知乎 编辑:程序博客网 时间:2024/06/02 07:28

TogleButton

  • 功能:有选中和未选中两种状态,并且为不同的状态设置不同的显示文本。

  • 属性:
    android:checked=”true”//选中状态,默认为false
    android:textOff=”关”//未选中显示文本
    android:textOn=”开”//选中状态显示文本

  • 效果:这里写图片描述
    这里写图片描述

  • 实现思路:在xml布局文件中设置一个ToggleButton和一个ImageView。在Activity文件中初始化ToggleBuuton控件,设置tb的OnCheckedChangeListener监听器,重写监听器的onCheckedChanged()方法,通过该方法的传入参数isChecked,判断tb的状态,改变相应图片。

tog_bt.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" >    <ToggleButton         android:id="@+id/toggleButton"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:textOn="开"        android:textOff="关"        android:checked="false"        />    <ImageView         android:id="@+id/imageView"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:background="@drawable/off"        /></LinearLayout>

TogBtActivity.java

package com.example.autodemo;import android.support.v7.app.ActionBarActivity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.widget.CompoundButton;import android.widget.CompoundButton.OnCheckedChangeListener;import android.widget.ImageView;import android.widget.ToggleButton;public class TogBtActivity extends ActionBarActivity implements OnCheckedChangeListener{    private ToggleButton tb;    private ImageView img;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.tog_bt);        //初始化控件        tb=(ToggleButton) findViewById(R.id.toggleButton);        img=(ImageView) findViewById(R.id.imageView);        /**         * 给当前toggleButton设置监听器         */        tb.setOnCheckedChangeListener(this);    }    /**     * 继承onCheckedChangeListener接口后,重写onCheckedChanged方法     *      * 当tb被点击的时候,当前的方法会被执行,更换img的背景     *      * @param buttonView---代表被点击控件的本身     * @param isChecked---代表被点击的控件的状态     *      */    @Override    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {        //使用三目运算符,判断isChecked的状态,更换相应的img        img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);    }}
0 0