Demo2\togglebutton_demo\src\main\res\layout\activity_main.xml
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:orientation="vertical" 6 tools:context=".MainActivity"> 7 8 <!--定义一个ToggleButton按钮--> 9 <ToggleButton10 android:id="@+id/toggle"11 android:layout_width="wrap_content"12 android:layout_height="wrap_content"13 android:checked="true"14 android:textOff="横向排列"15 android:textOn="纵向排列" />16 <!--定义一个可以动态改变方向的线性布局-->17 <LinearLayout18 android:id="@+id/test"19 android:layout_width="match_parent"20 android:layout_height="match_parent"21 android:orientation="vertical">22 23 <Button24 android:layout_width="wrap_content"25 android:layout_height="wrap_content"26 android:text="第一个按钮"/>27 <Button28 android:layout_width="wrap_content"29 android:layout_height="wrap_content"30 android:text="第二个按钮"/>31 <Button32 android:layout_width="wrap_content"33 android:layout_height="wrap_content"34 android:text="第三个按钮"/>35 </LinearLayout>36 37 </LinearLayout>
Demo2\togglebutton_demo\src\main\java\com\ly\togglebutton_demo\MainActivity.java
1 import android.app.Activity; 2 import android.os.Bundle; 3 import android.widget.CompoundButton; 4 import android.widget.LinearLayout; 5 import android.widget.ToggleButton; 6 7 public class MainActivity extends Activity { 8 private ToggleButton toggle ; 9 private LinearLayout linear ;10 @Override11 protected void onCreate(Bundle savedInstanceState) {12 super.onCreate(savedInstanceState);13 setContentView(R.layout.activity_main);14 toggle = (ToggleButton) findViewById(R.id.toggle);15 linear = (LinearLayout) findViewById(R.id.test);16 toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {17 @Override18 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {19 if (isChecked){20 //如果选中了,就设置垂直布局21 linear.setOrientation(LinearLayout.VERTICAL);22 }else {23 //否则就水平24 linear.setOrientation(LinearLayout.HORIZONTAL);25 }26 }27 });28 }29 30 31 }