ToggleButton学习

用ToggleButton实现一个线性布局在水平布局与垂直布局之间转换

xml配置

<LinearLayout  xmlns: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"
    android:orientation="vertical" >
    <ToggleButton android:id="@+id/tbut"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="横向排列"
        android:textOff="纵向排列"
        android:checked="true"/>
    <LinearLayout android:id="@+id/llayout_change"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#0000ff"
            android:textSize="30sp"
            android:text="1号"/>
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#00ff00"
            android:textSize="30sp"
            android:text="2号"/>
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#ff00ff"
            android:textSize="30sp"
            android:text="3号"/>
    </LinearLayout>
</LinearLayout >

代码编写:

package com.example.test2;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnAttachStateChangeListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.ToggleButton;

public class MainActivity extends Activity implements OnCheckedChangeListener{

	private LinearLayout llayout;
	private ToggleButton tbut;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        llayout=(LinearLayout) findViewById(R.id.llayout_change);
        tbut=(ToggleButton) findViewById(R.id.tbut);
        tbut.setOnCheckedChangeListener(this);
    }

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if(isChecked)
		{
			llayout.setOrientation(1);
		}
		else
		{
			llayout.setOrientation(0);
		}
	}
    
}
效果展示:

ToggleButton学习_第1张图片


ToggleButton学习_第2张图片

你可能感兴趣的:(ToggleButton学习)