如何利用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
-
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 truetextOff 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>
效果图:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。