您的位置:首页 > 移动开发 > Android开发

Android——使用多状态按钮ToggleButton(自己动手 丰衣足食)

2014-10-29 22:31 369 查看
最近在看慕课网的Android教程,其中的一节主要介绍开关按钮ToggleButton的 有一个小例子,控制灯泡的开关,下边是代码,(虽然很简单,但还是困难重重,先是clean clean 再clean把R文件都弄没啦,导入照片的时候自己不懂在每个文件夹下都导入了照片,以为分辨率不同的照片系统会自己选择,没想到只要一个就行)

布局文件layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="false"
android:textOn="开"
android:textOff="关"
/>

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

</LinearLayout>


activity:

package com.oct;

import android.app.Activity;
import android.os.Bundle;
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.line);

tb=(ToggleButton) findViewById(R.id.toggleButton1);
img=(ImageView) findViewById(R.id.imageView1);

tb.setOnCheckedChangeListener(this);
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//更改tb的状态,该参数代表当前Togglebutton是否被选中
tb.setChecked(isChecked);
img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);//为img更换背景图片

}
}


再附上自己P稍微改变的两张照片,和运行后的截图







内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: