您的位置:首页 > 其它

使用ToggleButton按钮实现开关效果

2016-03-17 20:17 531 查看
关于ToggleButton,有选中和未选中状态。在两种情况下还需要设置不同的文本内容。ToggleButton有以下几个属性:
android:isChecked="true";
android:textOn="开"
android:textOff="关"
开与关的内容自己可以设置成适用的不同内容。

目标:在点击ToggleButton状态为true时,显示灯泡发亮的图片;状态为false时,显示灯泡熄灭的图片。

一、编写布局文件。添加ToggleButton与imageView控件。代码如下:
<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" android:orientation="vertical" tools:context=".MainActivity">

<!-- texton:true    textoff:false -->

<togglebutton android:id="@+id/toggleButton1" android:layout_width="match_parent" android:layout_height="wrap_content" android:checked="false" android:textoff="关" android:texton="开">

<imageview android:id="@+id/imageView1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/off">

</imageview></togglebutton></linearlayout>


二、在Activity中实现逻辑部分。请看代码:
package com.nanhai.togglebutton;

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

public class MainActivity extends Activity implements OnCheckedChangeListener {
private ToggleButton tb;
private ImageView img;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化控件
tb = (ToggleButton) findViewById(R.id.toggleButton1);
img = (ImageView) findViewById(R.id.imageView1);

/*
* 给当前tb设置监听器
*/
tb.setOnCheckedChangeListener(this);
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
/*
* 当tb被点击的时候,当前的方法会执行
*
* buttonView代表被点击控件的本身
*
* isChecked代表被点击控件的状态
*
* 当控件被点击的时候,更换图片
*/

img.setBackgroundResource(isChecked ? R.drawable.on : R.drawable.off);
}

}


以上的内容即可完成使用ToggleButton按钮实现开关效果。效果如下图:



ps:如果有所疑惑,请戳链接http://download.csdn.net/detail/programmerteny/9464863下载对应源码研究学习。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ToggleButton