状态开关按钮ToggleButton的简单使用:实现动态控制布局

来源:互联网 发布:最新windows手机 编辑:程序博客网 时间:2024/04/29 03:12

ToggleButton是有Button派生出来的。从界面上来看,它与CheckBox复选框非常相似,它们都可以提供两个状态。不过ToggleButton与CheckBox的区别主要体现在功能上,ToggleButton通常用于切换程序中的某种状态。ToggleButton所支持的XML属性及方法如下:

下面通过一个简单实例来演示ToggleButton的使用,实现动态控制布局,代码如下:

Activity:

package com.lovo;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;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);// 通过findViewById得到ToggleButton对象ToggleButton toggle = (ToggleButton) findViewById(R.id.toggle);// 获得可以改变方向的线性布局对象final LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout1);toggle.setOnCheckedChangeListener(new OnCheckedChangeListener() {@Overridepublic void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {if (isChecked) {// 设置LinearLayout为垂直布局linearLayout.setOrientation(1);} else {// 设置LinearLayout为水平布局linearLayout.setOrientation(0);}}});}}


布局XML:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <ToggleButton        android:id="@+id/toggle"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:checked="true"        android:textOff="横向排列"        android:textOn="纵向排列" />    <!-- 定义一个可以动态改变方向的线性布局 -->    <LinearLayout        android:id="@+id/linearLayout1"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="vertical" >        <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>


附上图片效果: