开关控件Switch和ToggleButton
Switch和ToggleButtn都是开关按钮,我们在WLAN、GPS常用开关控制。
成都创新互联公司技术团队十载来致力于为客户提供网站制作、成都网站建设、品牌网站设计、成都营销网站建设、搜索引擎SEO优化等服务。经过多年发展,公司拥有经验丰富的技术团队,先后服务、推广了上千余家网站,包括各类中小企业、企事单位、高校等机构单位。
一、设计界面
1、打开“res/layout/activity_main.xml”文件。
从工具栏向activity拖出1个Switch开关按钮、1个ToggleButton按钮。

2、打开activity_main.xml文件。
代码如下:
二、程序文件
打开“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();
}
});
}
}三、运行效果


新闻标题:开关控件Switch和ToggleButton
文章路径:http://www.jxjierui.cn/article/gpiish.html


咨询
建站咨询
