Android 開關控制元件Switch的簡單使用
阿新 • • 發佈:2019-02-05
在很多app的設定頁面,或者是一些功能的開關介面,我們常常用到 Switch(開關) 來展示狀態,今天說說新學到的Switch控制元件。
最基本情況的按鈕:
<Switch
android:id="@+id/switch_普通開關"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
效果如圖:
簡單設定:
<pre name="code" class="html"> <Switch android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOff="" android:textOn="" android:switchMinWidth="120dp" android:thumb="@android:color/transparent" android:track="@drawable/switch_track" />
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/switch_close" android:state_checked="false" /> <item android:drawable="@drawable/switch_open" android:state_checked="true" /> </selector>
效果展示:
這裡layout_width:這能設定整個佈局的寬度,不能設定具體的Switch的大小,需要使用switchMinWidth屬性來設定。
thumb:文字所攜帶的背景,設定為背景色進行隱藏。不設定會出現一個背景框。
track:設定開關的背景圖片,類似於button的background。
textoff、texton:設定開關時的文字顯示。
最後說說Switch的點選事件:
private Switch mSwitch; private TextView mText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSwitch = (Switch) findViewById(R.id.switch_); mText = (TextView) findViewById(R.id.text_); // 新增監聽 mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked){ mText.setText("開啟"); }else { mText.setText("關閉"); } } }); }
如圖所示,沒什麼可以說的。。