Switch和ToggleButtn都是开关按钮,我们在WLAN、GPS常用开关控制。
一、设计界面
1、打开“res/layout/activity_main.xml”文件。
从工具栏向activity拖出1个Switch开关按钮、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="关" />
<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,在代码中可以
* 通过实现CompoundButton.OnCheckedChangeListener接口
* 并实现其内部类的onCheckedChanged来监听状态变化
*
*/
wlan.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
Toast.makeText(getApplicationContext(), "Switch状态为开", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Switch状态为关", Toast.LENGTH_LONG).show();
}
});
/*
* 因为ToggleButton组件继承自CompoundButton,在代码中可以通过实现
* CompoundButton.OnCheckedChangeListener接口,并实现
* 其内部类的onCheckedChanged来监听状态变化
*/
gps.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
Toast.makeText(getApplicationContext(), "ToggleButton状态为开", Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "ToggleButton状态为关", Toast.LENGTH_LONG).show();
}
});
}
}
三、运行效果
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。