您好,登錄后才能下訂單哦!
Switch和ToggleButtn都是開關(guān)按鈕,我們在WLAN、GPS常用開關(guān)控制。
一、設計界面
1、打開“res/layout/activity_main.xml”文件。
從工具欄向activity拖出1個Switch開關(guān)按鈕、1個ToggleButton按鈕。
2、打開activity_main.xml文件。
代碼如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Switch android:id="@+id/wlan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOn="開" android:textOff="關(guān)" /> <ToggleButton android:id="@+id/gps" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ToggleButton" /> </LinearLayout>
二、程序文件
打開“src/com.genwoxue.switchtogglebutton/MainActivity.java”文件。
然后輸入以下代碼:
import android.app.Activity; import android.os.Bundle; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.Switch; import android.widget.Toast; import android.widget.ToggleButton; public class MainActivity extends Activity { //聲明Switch private Switch wlan = null; private ToggleButton gps = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //獲取Switch對象、ToggleButton對象 wlan = (Switch) super.findViewById(R.id.wlan); gps = (ToggleButton) super.findViewById(R.id.gps); /* * 因為Switch組件繼承自CompoundButton,在代碼中可以 * 通過實現(xiàn)CompoundButton.OnCheckedChangeListener接口 * 并實現(xiàn)其內(nèi)部類的onCheckedChanged來監(jiān)聽狀態(tài)變化 * */ wlan.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) Toast.makeText(getApplicationContext(), "Switch狀態(tài)為開", Toast.LENGTH_LONG).show(); else Toast.makeText(getApplicationContext(), "Switch狀態(tài)為關(guān)", Toast.LENGTH_LONG).show(); } }); /* * 因為ToggleButton組件繼承自CompoundButton,在代碼中可以通過實現(xiàn) * CompoundButton.OnCheckedChangeListener接口,并實現(xiàn) * 其內(nèi)部類的onCheckedChanged來監(jiān)聽狀態(tài)變化 */ gps.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) Toast.makeText(getApplicationContext(), "ToggleButton狀態(tài)為開", Toast.LENGTH_LONG).show(); else Toast.makeText(getApplicationContext(), "ToggleButton狀態(tài)為關(guān)", Toast.LENGTH_LONG).show(); } }); } }
三、運行效果
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。