package?com.example.willow.myapplication5;
import?android.support.v7.app.AppCompatActivity;
import?android.os.Bundle;
import?android.widget.CompoundButton;
import?android.widget.ImageView;
import?android.widget.ToggleButton;
public?class?MainActivity5?extends?AppCompatActivity?implements?CompoundButton.OnCheckedChangeListener?{
????//設置控件對象對相關的控件進行操作
????private?ToggleButton?tb;
????private?ImageView?img;
????@Override
????protected?void?onCreate(Bundle?savedInstanceState)?{
????????super.onCreate(savedInstanceState);
????????setContentView(R.layout.activity_main5);
????????//初始化控件
????????tb?=?(ToggleButton)?findViewById(R.id.toggleButton);
????????img?=?(ImageView)findViewById(R.id.imageView);
????????/**
?????????*?給當前的tb按鈕設置監聽事件(監聽器)
?????????*/
????????tb.setOnCheckedChangeListener(this);
????}
????//重寫方法onCheckedChanged()
????public?void?onCheckedChanged(CompoundButton?buttonView,boolean?isChecked){
????????/**
?????????*?當tb被點擊的時候,當前的方法會執行
?????????*
?????????*?buttonView----代表被點擊控件的本身
?????????*?isChecked---代表被點擊的控件的狀態
?????????*
?????????*?當點擊這個tb的時候,更換img的背景
?????????*
?????????*/
????????img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);
????}
//????@Override
//????public?void?onPointerCaptureChanged(boolean?hasCapture)?{
//????????/**
//?????????*?當tb被點擊的時候,當前的方法會執行
//?????????*
//?????????*?buttonView----代表被點擊控件的本身
//?????????*?isChecked---代表被點擊的控件的狀態
//?????????*
//?????????*?當點擊這個tb的時候,更換img的背景
//?????????*
//?????????*/
//????????img.setBackgroundResource(hasCapture?R.drawable.on:R.drawable.off);
//????}
//????@Override
//????public?void?onCheckedChanged(CompoundButton?buttonView,?boolean?isChecked)?{
//
//????}
}
<?xml?version="1.0"?encoding="utf-8"?>
<android.support.constraint.ConstraintLayout?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=".MainActivity5">
????<!--textOff?fluse狀態?textOn?ture狀態??-->
????<ToggleButton
????????android:id="@+id/toggleButton"
????????android:checked="false"
????????android:textOff="@string/Off"
????????android:textOn="@string/turn"
????????android:layout_width="match_parent"
????????android:layout_height="wrap_content"
????????tools:layout_editor_absoluteX="72dp"
????????tools:layout_editor_absoluteY="16dp"?/>
????<!--android:src="@drawable/baign"-->
????<ImageView
????????android:id="@+id/imageView"
????????android:layout_width="match_parent"
????????android:layout_height="match_parent"
????????tools:layout_editor_absoluteX="136dp"
????????tools:layout_editor_absoluteY="228dp"?/>
</android.support.constraint.ConstraintLayout>
<resources>
????<string?name="app_name">ToggleButton</string>
????<string?name="turn">開</string>
????<string?name="Off">關</string>
</resources>
2018-10-22