UI组件之TextView及其子类(三)ToggleButton和Switch

ToggleButton、Switch、CheckBox和RadioButton都是继承自android.widget.CompoundButton,意思是可选择的,因此它们的使用方法都非常类似。

CompoundButton有两个状态,各自是checked和not checked。

ToggleButton的属性:



Switch组件的属性:


android:thumb是选中时的背景

例:开关button控制布局方向

main.xml

<?xml version="1.0" encoding="utf-8"?

> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ToggleButton android:id="@+id/toggleButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ToggleButton" android:textOff="横向排列" android:textOn="纵向排列" /> <!-- android:thumb="@drawable/check" 使用自己定义的drawable对象绘制开关按钮 --> <Switch android:id="@+id/switch1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Switch" android:textOff="横向排列" android:textOn="纵向排列" android:thumb="@drawable/check" /> <LinearLayout android:id="@+id/root" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button1" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button2" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button3" /> </LinearLayout> </LinearLayout>


MainActivity.java

	ToggleButton toggle;
	Switch switcher;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         toggle=(ToggleButton) findViewById(R.id.toggleButton1);
         switcher=(Switch) findViewById(R.id.switch1);
         
         final LinearLayout test=(LinearLayout) findViewById(R.id.root);
         //ToggleButton和Switch的监听接口和复选框CheckButton的一样
         CompoundButton.OnCheckedChangeListener listener=new  CompoundButton.OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(CompoundButton button, boolean checkedId) {
				// TODO Auto-generated method stub
				if(checkedId){
					//1表示垂直布局,0表示水平布局
					test.setOrientation(1);
				}else{
					test.setOrientation(0);
				}
				}     	 
         };
         
         toggle.setOnCheckedChangeListener(listener);
         switcher.setOnCheckedChangeListener(listener);
    }



以后要学会自己定制跟家美观的组件

推荐几个好的博客:

http://blog.csdn.net/billpig/article/details/6634481

http://blog.csdn.net/luoweifu/article/details/11752035









原文地址:https://www.cnblogs.com/yjbjingcha/p/7020280.html