随笔 - 1357  文章 - 0  评论 - 1104  阅读 - 1941万

Android控件之ToggleButton探究

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

以下案例为ToggleButton的用法

目录结构

main.xml布局文件

复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation
="vertical"
android:layout_width
="fill_parent"
android:layout_height
="fill_parent">
<ImageView android:id="@+id/imageView"
android:layout_width
="wrap_content"
android:layout_height
="wrap_content"
android:src
="@drawable/bulb_off"
android:layout_gravity
="center_horizontal" />
<ToggleButton android:id="@+id/toggleButton"
android:layout_width
="140dip"
android:layout_height
="wrap_content"
android:textOn
="开灯"
android:textOff
="关灯"
android:layout_gravity
="center_horizontal" />
</LinearLayout>
复制代码

ToggleButtonActivity类

复制代码
package com.ljq.tb;

import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ToggleButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class ToggleButtonActivity extends Activity {
private ImageView imageView=null;
private ToggleButton toggleButton=null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

imageView
=(ImageView) findViewById(R.id.imageView);
toggleButton
=(ToggleButton)findViewById(R.id.toggleButton);
toggleButton.setOnCheckedChangeListener(
new OnCheckedChangeListener(){

public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
toggleButton.setChecked(isChecked);
imageView.setImageResource(isChecked
?R.drawable.bulb_on:R.drawable.bulb_off);
}

});
}
}
复制代码

运行效果:

posted on   Ruthless  阅读(8006)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
< 2011年2月 >
30 31 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 1 2 3 4 5
6 7 8 9 10 11 12

点击右上角即可分享
微信分享提示