Android控件之Switch
1 Switch簡介
Switch用於開關按鈕。Switch和ToggleButton稍有區別:ToggleButton是按下彈起的開關,而Switch是左右滑動的開關。
2 Switch示例
創建一個activity,包含1個Switch。
應用層代碼
package com.skywang.control; import android.os.Bundle; import android.app.Activity; import android.view.View; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.Switch; import android.widget.TextView; public class MySwitch extends Activity { private Switch mSwitch; private TextView mViewShow; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.my_switch); mViewShow = (TextView)findViewById(R.id.tv_show); // 設置Switch開關
mSwitch = (Switch)findViewById(R.id.switch_def); mSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener(){ public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { if (isChecked) { // 開啟switch,設置提示信息
mViewShow.setText(getString(R.string.text_on)); } else { // 關閉swtich,設置提示信息
mViewShow.setText(getString(R.string.text_off)); } } }); } }
layout文件
<LinearLayout 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:orientation="vertical"
>
<TextView android:id="@+id/tv_show" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOn="@string/text_def"
/>
<Switch android:id="@+id/switch_def" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOn="@string/text_on" android:textOff="@string/text_off"
/>
</LinearLayout>
注意:
若提示錯誤“View requires API level 14 (current min is 10): <Switch>”。
那是Switch的最小版本必須是API level14(即Android4.0版本),因為Switch是Android4.0支持的。
解決辦法:
在manifest中修改最小的sdk版本為14(即Android4.0版本),添加如下內容即可
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
manifest文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.skywang.control" android:versionCode="1" android:versionName="1.0" >
<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="17" />
<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >
<activity android:name="com.skywang.control.MySwitch" android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
點擊下載:源代碼
運行效果:如圖

