安卓控件使用系列11:ToggleButton开关控件的使用

这篇博客介绍安卓中的ToggleButtom控件,常见于开关网络和手电筒功能。通过实例,展示了如何利用ToggleButton控制Button的横纵排列切换,主要涉及XML布局和活动中的事件监听处理。
摘要由CSDN通过智能技术生成

安卓中ToggleButton控件是开关控件,在开关网络信号、开关手电筒等功能中都有体现,下面我们将它的使用方法分享给大家。

这个例子实现的是使用开关控件ToggleButton控制布局中三个Button控件的水平和垂直编排的切换。

整体思路:在xml文件中定义三个BUtton控件和一个ToggleButton控件,然后在活动中找到LinearLayout的布局文件ID,在ToggleButton的onCheckedChanged事件中根据是否选中对这个布局的水平或垂直属性进行切换。

activity_main.xml文件:

<LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    >
    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
        
        <ToggleButton 
            android:id="@+id/togglebutton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:textOn="纵向排列"
            android:textOff="横向排列"
            />
    </LinearLayout>
    <LinearLayout 
        android:id="@+id/mylayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        >
        <Button 
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            />
        <Button 
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            />
        <Button 
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button"
            />
    </LinearLayout>
    </LinearLayout>
MainActivity.java文件:

private ToggleButton toggleButton;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		toggleButton=(ToggleButton)findViewById(R.id.togglebutton);
		final LinearLayout linearLayout=(LinearLayout)findViewById(R.id.mylayout);
		toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
				// TODO Auto-generated method stub
				if(isChecked){
					linearLayout.setOrientation(1);//设置为垂直布局
				}else{
					linearLayout.setOrientation(0);//设置为水平布局
				}
			}
		});
	}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值