前段
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.app.MainActivity">
//textOn 是改变控件名称的语句
<ToggleButton
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/toggleButton1"
android:textOn="开"
android:textOff="关"
/>
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/toggleButton1"
android:background="@drawable/off"
android:id="@+id/imageView1"
/>
</RelativeLayout>
后端 接口监听器
package com.example.app;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener{
private ToggleButton bt1;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1= (ToggleButton) findViewById(R.id.toggleButton1);
imageView= (ImageView) findViewById(R.id.imageView1);
bt1.setOnCheckedChangeListener(this);
}
/*先初始化控件
*给bt1设置监听器,接口类监听器,来监听控件现在是何种状态
*
*
*/
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
imageView.setBackgroundResource(b?R.drawable.on:R.drawable.off);//改变imageview背景资源
//当tb被点击之后,方法被执行,compoundButton检测当前是什么按钮
}
}