Android控件之ToggleButton、Switch

1、開關控件ToggleButton、Switch控件簡介

該控件起到一個開關的作用,類似於在Android手機中的,打開藍牙等功能。第一張圖是ToggleButton的佈局效果,第二張是Switch的佈局效果。


2、相關代碼

在xml中的佈局代碼:

<span style="font-size:10px;"><ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:textOn="開"
        android:textOff="關"
        android:checked="true" />
	<Switch
        android:id="@+id/open"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOff="藍牙關閉中"
        android:textOn="藍牙開啓中" /></span>
屬性介紹:

android:textOff      關閉狀態顯示的文字,默認值:Off

android:textOn      打開狀態顯示的文字,默認值:On

android:checked    界面首次展示時,該控件是關閉還是打開的狀態,默認值:關閉

單擊事件:

CompoundButton.OnCheckedChangeListener

package com.example.togglebtnratingbar;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity implements CompoundButton.OnCheckedChangeListener {
	private ToggleButton toggleButton1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		toggleButton1 = (ToggleButton) this.findViewById(R.id.toggleButton1);
		// 綁定單擊事件
		toggleButton1.setOnCheckedChangeListener(this);
	}
	// 處理單擊事件
	@Override
	public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked) {
		if (R.id.toggleButton1 == toggleButton.getId()) {
			if (isChecked){
				Toast.makeText(this, "開", Toast.LENGTH_SHORT).show();
			}else {
				Toast.makeText(this, "關", Toast.LENGTH_SHORT).show();
			}
		}
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}




發佈了32 篇原創文章 · 獲贊 10 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章