【实验目的】
1.掌握ToggleButton的使用方法。
【实验原理】
ToggleButton(开关按钮)继承自CompoundButton,是一个具有选中和未选中两种状态的按钮,并可为不同的状态设置不同的显示文本,常用于表示开/关场景中。
【实验内容】
本实验案例,通过ToggleButton实现一个开关灯的效果。效果如图1所示。
通过下面的开关按键,实现开关灯效果。
【练习步骤】
1.创建新项目
先建立一个空项目,如MyToggleButton项目,然后进行以下修改。
2.资源建设
(1)图片
从开、关灯的图片,存放在res/drawable目录下,文件名称分别为open.jpg、close.jpg。
3.设置主布局文件
修改主布局文件activity_main.xml,本例采用相对布局管理器,在其中添加ImageView、ToggleBuuton控件,并设置其相关属性,具体内容如下。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".MainActivity">
<ImageView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"
android:id="@+id/img_light_on"
android:layout_marginTop="71dp"
android:src="@drawable/close"/>
<ToggleButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true"
android:id="@+id/toggleButton"
android:layout_marginTop="63dp"
android:layout_below="@+id/img_light_on"
android:text="ToggleButton"/>
</RelativeLayout>
4.编写代码
程序代码主要实现两个Button的事件处理方法,具体代码如下。
package com.example.mytogglebutton;
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 {
private ImageView imageView;
private ToggleButton toggleButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.img_light_on);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton);
toggleButton.setTextOn("关灯");
toggleButton.setTextOff("开灯");
toggleButton.setChecked(false);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
imageView.setImageResource(R.drawable.open);
}else {
imageView.setImageResource(R.drawable.close);
}
}
});
}
}
5.验证效果
编译运行,可通过关灯/开关按钮,实现开关灯效果,效果如图1所示。