安卓ToggleButton的使用

安卓ToggleButton的使用

以下的实例,实现点击排列按钮,实现三个测试按钮布局的切换功能。

安卓ToggleButton的使用

main.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"
    tools:context=".MainActivity" >

    <!--定义一个ToggleButton按钮-->
    <ToggleButton android:id="@+id/toggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOff="横向排列"
        android:textOn="纵向排列"
        android:checked="false" 
        />
    
    <!-- 定义一个可以动态改变方向的线性布局 -->
    <LinearLayout android: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

package com.example.togglebuttontest;

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

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ToggleButton toggle=(ToggleButton) super.findViewById(R.id.toggle);
final LinearLayout test=(LinearLayout) super.findViewById(R.id.test);
toggle.setOnCheckedChangeListener(new OnCheckedChangeListener(){

@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
//如果选中的话
if(arg1){
//设置LinearLayout垂直布局,0表示水平布局
test.setOrientation(0);
}
else{
//设置LinearLayout水平布局,1表示垂直布局
test.setOrientation(1);
}
}
});
}


}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值