MainActivity.java:
import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.LinearLayout; import android.widget.ToggleButton; /** * ToggleButton 开关状态按钮控件 * * @author Caesar * */ public class MainActivity extends Activity { private ToggleButton toggleButtonbutton; private LinearLayout linearLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toggleButtonbutton = (ToggleButton) findViewById(R.id.togglebutton); linearLayout = (LinearLayout) findViewById(R.id.mylayout); toggleButtonbutton.setOnCheckedChangeListener(new MyOnCheckedChangeListener() ); } public class MyOnCheckedChangeListener implements OnCheckedChangeListener{ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // TODO Auto-generated method stub if (isChecked){ linearLayout.setOrientation(1);//表示设置垂直布局 }else { linearLayout.setOrientation(0);//设置水平布局 } } } }
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.togglebuttondemo.MainActivity" > <ToggleButton android:id="@+id/togglebutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:textOff="横向排列" android:textOn="纵向排列" /> <LinearLayout android:id="@+id/mylayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button" /> </LinearLayout> </LinearLayout>
Android---19---ToggleButton开关按钮
原文地址:http://blog.csdn.net/u013476556/article/details/45101277