![安卓ToggleButton的使用 安卓radiobutton使用](http://img.aihuau.com/images/01111101/01075955t015979ee8d028ba16d.png)
以下的实例,实现点击排列按钮,实现三个测试按钮布局的切换功能。
main.xml
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"android:layout_height="match_parent" tools:context=".MainActivity">
<!--定义一个ToggleButton按钮--> <ToggleButtonandroid:id="@+id/toggle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textOff="横向排列" android:textOn="纵向排列" android:checked="false" /> <!-- 定义一个可以动态改变方向的线性布局--> <LinearLayoutandroid:id="@+id/test" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/button1" android:layout_width=" wrap_content" android:layout_height="wrap_content" android:text="测试1"/> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试2"/> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试3"/>
</LinearLayout>
</LinearLayout>
MainActivity.java
packagecom.example.togglebuttontest;
importandroid.os.Bundle;importandroid.app.Activity;importandroid.view.Menu;importandroid.widget.CompoundButton;importandroid.widget.CompoundButton.OnCheckedChangeListener;importandroid.widget.LinearLayout;importandroid.widget.ToggleButton;
public class MainActivityextends Activity {
@Overrideprotected void onCreate(BundlesavedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);ToggleButtontoggle=(ToggleButton) super.findViewById(R.id.toggle);final LinearLayouttest=(LinearLayout) super.findViewById(R.id.test);toggle.setOnCheckedChangeListener(newOnCheckedChangeListener(){
@Overridepublic voidonCheckedChanged(CompoundButton arg0, boolean arg1) {//如果选中的话if(arg1){//设置LinearLayout垂直布局,0表示水平布局test.setOrientation(0);}else{//设置LinearLayout水平布局,1表示垂直布局test.setOrientation(1);}}});}
}