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. }  

猜你喜欢

转载自blog.csdn.net/qq_29586601/article/details/79851717