Android開關控件Switch的使用案例
更新時間:2019年03月29日 08:57:55 作者:徐劉根
今天小編就為大家分享一篇關于Android開關控件Switch的使用案例,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
在很多app的設置頁面,或者是一些功能的開關界面,我們常常用到 Switch(開關) 來展示狀態(tài),今天說說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;
}
}
實現(xiàn)效果如下:

總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
您可能感興趣的文章:
- Android CheckBox中設置padding無效解決辦法
- Android開發(fā)之CheckBox的簡單使用與監(jiān)聽功能示例
- Android 中CheckBox多項選擇當前的position信息提交的示例代碼
- Android 中CheckBox的isChecked的使用實例詳解
- Android開發(fā)手冊自定義Switch開關按鈕控件
- Android 自定義Switch開關按鈕的樣式實例詳解
- Android UI控件Switch的使用方法
- Android單選按鈕RadioButton的使用方法
- Android復選框CheckBox與開關按鈕Switch及單選按鈕RadioButton使用示例詳解
相關文章
Android EditText默認不彈出輸入法的實現(xiàn)方法
下面小編就為大家分享一篇Android EditText默認不彈出輸入法的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-01-01
Android組件TabHost實現(xiàn)頁面中多個選項卡切換效果
這篇文章主要為大家詳細介紹了Android組件TabHost實現(xiàn)頁面中多個選項卡切換效果的相關資料,感興趣的小伙伴們可以參考一下2016-05-05

