。。。
实例代码:
前端代码:
<?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"
>
<!--
开关按钮:
android:textOn = "开":开关处于打开状态时显示的文字
android:textOff = "关":开关处于关闭状态时显示的文字
-->
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="开"
android:textOff="关"
android:id="@+id/toggleButton"
android:layout_gravity="center_horizontal"
/>
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="开关按钮"
android:textOn="on"
android:textOff="off"
android:id="@+id/switch1"
android:layout_gravity="center_horizontal"
android:checked="false" />
//android:id="@id/switch1":如果是switch,会跟java中的关键字产生冲突
</LinearLayout>
业务逻辑:
package com.example.tf.togglebutton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private ToggleButton toggleButton;
private Switch Switch1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//寻找控件
this.toggleButton = (ToggleButton) this.findViewById(R.id.toggleButton);
//注册监听器
this.toggleButton.setOnCheckedChangeListener(this);
//寻找控件
this.Switch1 = (Switch) this.findViewById(R.id.switch1);
//注册监听器
this.Switch1.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String text = null ;
//对象名 instanceof 类名 : 判断对象是不是由类是实例化的
if(buttonView instanceof ToggleButton){
text = ((ToggleButton)buttonView).getText().toString();
}else if(buttonView instanceof Switch){
Switch switch1 = ((Switch)buttonView);
if (isChecked){
text = switch1.getTextOn().toString();
}else{
text = switch1.getTextOff().toString();
}
}
Toast.makeText(this, "text="+ text, Toast.LENGTH_SHORT).show();
if(isChecked){
}else{
}
}
}