服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - Android控件之ToggleButton的使用方法

Android控件之ToggleButton的使用方法

2021-01-12 15:21Android开发网 Android

本篇文章介绍了,Android控件之ToggleButton的使用方法。需要的朋友参考下

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

以下案例为togglebutton的用法

目录结构

Android控件之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类

  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.  
  9. public class ToggleButtonActivity extends Activity { 
  10.     private ImageView imageView=null
  11.     private ToggleButton toggleButton=null
  12.  
  13.     @Override 
  14.     public void onCreate(Bundle savedInstanceState) { 
  15.         super.onCreate(savedInstanceState); 
  16.         setContentView(R.layout.main); 
  17.  
  18.         imageView=(ImageView) findViewById(R.id.imageView); 
  19.         toggleButton=(ToggleButton)findViewById(R.id.toggleButton); 
  20.         toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener(){ 
  21.  
  22.             public void onCheckedChanged(CompoundButton buttonView, 
  23.                     boolean isChecked) { 
  24.                 toggleButton.setChecked(isChecked); 
  25.                 imageView.setImageResource(isChecked?R.drawable.bulb_on:R.drawable.bulb_off); 
  26.             } 
  27.  
  28.         }); 
  29.     } 
 

运行效果:

Android控件之ToggleButton的使用方法

延伸 · 阅读

精彩推荐