如何利用ToggleButton切换图片

本文介绍了一个简单的Android应用案例,使用ToggleButton控件切换ImageView的背景图片。通过实现CompoundButton.OnCheckedChangeListener接口,根据ToggleButton的状态改变来更新ImageView的显示内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何利用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>

    效果图:

图片描述
图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值