1

如何利用ToggleButton切换图片
java文件

    package com.example.administrator.app;
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.CompoundButton;
    import android.widget.ImageView;
    import android.widget.ToggleButton;
    public class toggleBtn extends Activity implements    CompoundButton.OnCheckedChangeListener {
    private ToggleButton tb;
    private ImageView img;
    protected void onCreate(Bundle saveInstanceState){
    super.onCreate(saveInstanceState);
    setContentView(R.layout.togglebutton);
    tb = (ToggleButton)findViewById(R.id.toggle_button);
    img = (ImageView) findViewById(R.id.imageView);
    /**
    • 给当前的tb设置监听器
      */
      tb.setOnCheckedChangeListener(this);

    }

     //Called when the checked state of a compound button has changed.
     //@param buttonView The compound button view whose state has changed.
     //@param isChecked  The new checked state of buttonView.

    @Override

    1. void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

         
           //实现接口CompoundButton.OnCheckedChangeListener 来设置tb监听,当点击  按钮tb的时候开始执行
          // onCheckedChanged方法
          //buttonView 代表被点击的控件按钮
          // isChecked  被点击控件的状态
          //当点击tb开关的时候,更换img的背景
         img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);
      }

      }
      布局文件
      <?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">
      <!--textOn true

         textOff false-->
       <ToggleButton
         android:checked="false"
         android:textOff="关"
         android:textOn="开"
         android:id="@+id/toggle_button"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"/>
      
       <ImageView
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:id="@+id/imageView"
         android:background="@drawable/off"/>
      </LinearLayout>

      效果图:

    图片描述
    图片描述


    MichaelDuan
    1.8k 声望39 粉丝