xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <!-- 定义一个ToggleButton按钮 --> <ToggleButton android:id="@+id/toggle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOff="横向排列" android:textOn="纵向排列" android:checked="true" /> <!-- 定义一个可以动态改变方向的线性布局 --> <LinearLayout android:id="@+id/test" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试按钮一" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试按钮二" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试按钮三" /> </LinearLayout> </LinearLayout>
MainActivity
package org.crazyit.togglebutton; import android.app.Activity; import android.os.Bundle; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout; import android.widget.ToggleButton; /** * Description: * <br/>site: <a href="http://www.crazyit.org">crazyit.org</a> * <br/>Copyright (C), 2001-2012, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @author Yeeku.H.Lee [email protected] * @version 1.0 */ public class ToggleButtonTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ToggleButton toggle = (ToggleButton)findViewById(R.id.toggle); final LinearLayout test = (LinearLayout)findViewById(R.id.test); toggle.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton arg0, boolean arg1) { if(arg1) { //设置LinearLayout垂直布局 test.setOrientation(1); } else { //设置LinearLayout水平布局 test.setOrientation(0); } } }); } }