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>