按下去會呈現ON,再按一下就呈現OFF
以下是該專案原始碼:
package com.cyfang.toggle;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.ToggleButton;
public class ToggleMain extends Activity {
private ToggleButton toggleButton = null;
private TextView textView = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_toggle_main);
toggleButton = (ToggleButton) findViewById(R.id.toggleButton1);
toggleButton.setOnClickListener(clickListener);
textView = (TextView) findViewById(R.id.textView);
}
private OnClickListener clickListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (((ToggleButton) v).isChecked()) { // 取得按鈕狀態
textView.setText("觸發按鈕");
} else {
textView.setText("尚未觸發按鈕");
}
}
};
}
activity_toggle_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="187dp"
android:text="ToggleButton" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/toggleButton1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="101dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
點擊第一次時則會改變TextView文字為『觸發按鈕』
點擊第二次時則會改變TextView文字為『尚未觸發按鈕』
這章只介紹比較簡單的基本用法,等之後如果有使用到這個物件在寫下去摟

