Android中使用ToggleButton(开关按钮)按钮实现的灯泡开关效果

示例图:



activity.xml文件布局


[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  5.     xmlns:tools="http://schemas.android.com/tools"  
  6.     android:layout_width="match_parent"  
  7.     android:layout_height="match_parent"  
  8.     tools:context="com.yongninggo.helloworld1.MainActivity"  
  9.     android:orientation="vertical">  
  10.   
  11.     <ToggleButton  
  12.         android:id="@+id/togbutton"  
  13.         android:layout_width="match_parent"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_marginTop="5dip"  
  16.         android:textOff="关"  
  17.         android:textOn="开"/>  
  18.   
  19.     <ImageView  
  20.         android:id="@+id/image1"  
  21.         android:layout_width="match_parent"  
  22.         android:layout_height="match_parent"  
  23.         android:src="@drawable/image1"/>  
  24.   
  25. </LinearLayout>  


Activity.Java文件

[java] view plain copy
  1. package com.yongninggo.helloworld1;  
  2.   
  3. import android.os.Bundle;  
  4. import android.support.v7.app.AppCompatActivity;  
  5. import android.widget.CompoundButton;  
  6. import android.widget.ImageView;  
  7. import android.widget.ToggleButton;  
  8.   
  9. public class Activity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {  
  10.   
  11.     private ToggleButton toggleButton;  
  12.     private ImageView imageView;  
  13.   
  14.     @Override  
  15.     protected void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.activity);  
  18.   
  19.         toggleButton = (ToggleButton) findViewById(R.id.togbutton);  
  20.         imageView = (ImageView) findViewById(R.id.image1);  
  21.         toggleButton.setOnCheckedChangeListener(this);  
  22.     }  
  23.   
  24.     @Override  
  25.     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {  
  26.         toggleButton.setChecked(isChecked);  
  27.         imageView.setImageResource(isChecked ? R.drawable.image1 : R.drawable.image2);  
  28.   
  29.     }  
  30. }  

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值