1、首先打开Android编程工具,其实无所谓哪一种工具,我用的Eclipse
2、先添加几个控件,设置为垂直显示,代码如下<L坡纠课柩inearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" tools:context=".MainActivity" > <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>显示效果,如图显示
3、然后编写核心代码,代码如下public class MainActivity extends Activit烤恤鹇灭y { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_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 buttonView, boolean isChecked) { if(isChecked){ //垂直 test.setOrientation(1); }else{ //水平 test.setOrientation(0); } } }); }
4、然后启动android虚拟机,进行调试,效果如下图所示