package com.example.exercise;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
/**
* 此类主要是用来展示ToggleButton该如何使用
* @author Administrator
*
*/
public class ToggleButtonActivity extends Activity{
ToggleButton toggleButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tb_view);
toggleButton = (ToggleButton) findViewById(R.id.my_switch);
toggleButton.setOnCheckedChangeListener(changeListener);
}
OnCheckedChangeListener changeListener = new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
Toast.makeText(ToggleButtonActivity.this, isChecked?"开关打开了":"开关关闭了", Toast.LENGTH_SHORT).show();
}
};
}
<?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" >
<!-- 当checked位false的时候,显示textOff的内容;当checked为true的时候,显示textOn的内容 -->
<ToggleButton
android:id="@+id/my_switch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textOn="开"
android:textOff="关"
android:checked="false"
/>
</LinearLayout>