1.ToggleButton
(1)介绍
(2)组件形状
(3)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" android:orientation="vertical" tools:context=".MainActivity"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <!--设置背景颜色,ToggleButton 默认灰色背景看不出来--> <ToggleButton android:id="@+id/toggleButton2" android:layout_width="100dp" android:layout_height="wrap_content" android:text="ToggleButton" android:background="#000fff" android:textOff="关灯" android:textOn="开灯" /> <ImageView android:id="@+id/imageView" android:layout_width="200dp" android:layout_height="300dp" app:srcCompat="@mipmap/img1" /> </LinearLayout> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="100dp" android:layout_marginTop="20dp" android:background="#345555" android:orientation="horizontal"> <Switch android:id="@+id/switch1" android:layout_width="200dp" android:layout_height="100dp" android:layout_weight="1" android:text="客厅灯开关" /> </LinearLayout> </LinearLayout>
(4)后台代码
package com.lucky.test22; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.Switch; import android.widget.ToggleButton; public class MainActivity extends AppCompatActivity { ToggleButton toggleButton; ImageView imageView; Switch aSwitch; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toggleButton=findViewById(R.id.toggleButton2); aSwitch=findViewById(R.id.switch1); imageView=findViewById(R.id.imageView); toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ imageView.setImageResource(R.mipmap.img1); //修改所显示的图片 }else { imageView.setImageResource(R.mipmap.img2); } } }); aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ imageView.setImageResource(R.mipmap.img1); //修改所显示的图片 }else { imageView.setImageResource(R.mipmap.img2); } } }); } }