Android控件之ToggleButton探究

ToggleButton的状态只能是选中和未选中,并且需要为不同的状态设置不同的显示文本。

以下案例为ToggleButton的用法

目录结构

1.png

2011-5-14 08:41:51 上传
下载附件 (10.57 KB)

main.xml布局文件

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:orientation="vertical"
  4.     android:layout_width="fill_parent"
  5.     android:layout_height="fill_parent">
  6.     <ImageView android:id="@+id/imageView"
  7.         android:layout_width="wrap_content"
  8.         android:layout_height="wrap_content"
  9.         android:src="@drawable/bulb_off"
  10.         android:layout_gravity="center_horizontal" />
  11.     <ToggleButton android:id="@+id/toggleButton"
  12.         android:layout_width="140dip"
  13.         android:layout_height="wrap_content"
  14.         android:textOn="开灯"
  15.         android:textOff="关灯"
  16.         android:layout_gravity="center_horizontal" />
  17. </LinearLayout>
复制代码



ToggleButtonActivity类

  1. package com.ljq.tb;

  2. import android.app.Activity;
  3. import android.os.Bundle;
  4. import android.widget.CompoundButton;
  5. import android.widget.ImageView;
  6. import android.widget.ToggleButton;
  7. import android.widget.CompoundButton.OnCheckedChangeListener;

  8. public class ToggleButtonActivity extends Activity {
  9.     private ImageView imageView=null;
  10.     private ToggleButton toggleButton=null;
  11.    
  12.     @Override
  13.     public void onCreate(Bundle savedInstanceState) {
  14.         super.onCreate(savedInstanceState);
  15.         setContentView(R.layout.main);
  16.         
  17.         imageView=(ImageView) findViewById(R.id.imageView);
  18.         toggleButton=(ToggleButton)findViewById(R.id.toggleButton);
  19.         toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener(){

  20.             public void onCheckedChanged(CompoundButton buttonView,
  21.                     boolean isChecked) {
  22.                 toggleButton.setChecked(isChecked);
  23.                 imageView.setImageResource(isChecked?R.drawable.bulb_on:R.drawable.bulb_off);
  24.             }
  25.             
  26.         });
  27.     }
  28. }
复制代码



运行效果:

2.png

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值