码迷,mamicode.com
首页 > 移动开发 > 详细

android中switch和toggleButton

时间:2015-10-07 13:31:02      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:

状态开关按钮ToggleButton和开关Switch都是由Button派生而来,Button的所有属性和方法都适用,通常用于状态的切换。

1)activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!--定义一个状态开关按钮,开关关闭时横向排列,开关开启时纵向排列-->
<ToggleButton android:id="@+id/toggle"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textOff="横向排列"
android:textOn="纵向排列"
android:checked="true"/>
<!--定义一个开关,开关关闭时横向排列,开关开启时纵向排列-->
    <Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/switcher"
android:textOff="横向排列"
android:textOn="纵向排列"
android:thumb="@drawable/check"
android:checked="true"/>
<!--定义一个有三个按钮的线性布局,默认排列是纵向-->
<LinearLayout
android:layout_width="match_parent"
android:id="@+id/test"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮2"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按钮3"/>
</LinearLayout>
</LinearLayout>
2)MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.widget.*;

public class MainActivity extends Activity {
ToggleButton toggle;
Switch switcher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggle=(ToggleButton)findViewById(R.id.toggle);
switcher=(Switch)findViewById(R.id.switcher);
final LinearLayout test=(LinearLayout)findViewById(R.id.test);
/**
  CompoundButton是一个带有选中/未选中状态的按钮,当按钮按下时自动改变状态。toggleButton、switch都由它继承而来。isChecked用来表明按钮是否被选中。
*/
CompoundButton.OnCheckedChangeListener listener=new CompoundButton.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton button,boolean isChecked){
if(isChecked){
test.setOrientation(1);//线性布局为垂直。
toggle.setChecked(true);
switcher.setChecked(true);
}
else{
test.setOrientation(0);//线性布局为水平。
toggle.setChecked(false);
switcher.setChecked(false);
}
}
};
toggle.setOnCheckedChangeListener(listener);
switcher.setOnCheckedChangeListener(listener);
}
}

运行结果:

1)开关开启时:

技术分享

2)开关关闭时:

技术分享

android中switch和toggleButton

标签:

原文地址:http://www.cnblogs.com/bingningran/p/4858525.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!