示例图:
![](https://i-blog.csdnimg.cn/blog_migrate/437de28cd90e62d3078e152e5cb105d9.jpeg)
![](https://i-blog.csdnimg.cn/blog_migrate/ba22dc9d29ddd2436f287cd46e93f4db.jpeg)
activity.xml文件布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.yongninggo.helloworld1.MainActivity"
android:orientation="vertical">
<ToggleButton
android:id="@+id/togbutton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:textOff="关"
android:textOn="开"/>
<ImageView
android:id="@+id/image1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/image1"/>
</LinearLayout>
Activity.Java文件
package com.yongninggo.helloworld1;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ToggleButton;
public class Activity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private ToggleButton toggleButton;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
toggleButton = (ToggleButton) findViewById(R.id.togbutton);
imageView = (ImageView) findViewById(R.id.image1);
toggleButton.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
toggleButton.setChecked(isChecked);
imageView.setImageResource(isChecked ? R.drawable.image1 : R.drawable.image2);
}
}