首页 > 代码库 > Android学习笔记之Switch的使用案例

Android学习笔记之Switch的使用案例


(1)布局文件代码

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="94dp"
        android:text="开启震动"
        android:textOff="关闭"
        android:onClick="onToggleClicked"
        android:textOn="打开" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/switch1"
        android:layout_alignParentTop="true"
        android:layout_marginTop="26dp"
        android:text="Switch的使用"
        android:textSize="30dp" />

</RelativeLayout>

(2)控制的类

package com.example.android_switch;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Switch;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	public void onToggleClicked(View view) {
		/*
		 * 强转为Switch类型的
		 */
		boolean isChecked = ((Switch) view).isChecked();
		if (isChecked == true) {
			Toast.makeText(MainActivity.this, "打开", 1).show();
		} else {
			Toast.makeText(MainActivity.this, "关闭", 1).show();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
技术分享


Android学习笔记之Switch的使用案例