是个传颂厨

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

用一个开关实现两种状态,一个true执行一个命令,一个false执行一个命令。

先学习自慕课网。

先进行activity_main改写。

<?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:checked="false"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textOff="关"
        android:textOn="开" 
        />
    <!-- 加入状态开关 -->

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
<!-- 记得去除图片源 -->

然后这个演示是针对每个开关状态显示一个图片来说的,所以找到两个不同的图片加入到res/drawable中,一个名为on,一个名为off.

然后改写MainActivity文件

package com.deemo;


import android.app.Activity;
import android.media.Image;
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.activity_main);
        
        tb = (ToggleButton) findViewById(R.id.toggleButton1);//开关
        img = (ImageView) findViewById(R.id.imageView1);
        
        tb.setOnCheckedChangeListener(this);//设置监听
    }
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub
                //tb被点击时,当前方法被执行
                //buttonView被点击控件
                img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);
                //三目运算符,进行判断
    }

    
}

这个就可以在模拟器中运行了,但是这个还有一个小BUG,就是一开始不会显示off状态的图片,是一片空白。点击显示on状态显示对应图片,再点击off状态才会显示off对应图片出来,bug留在这里,以后回来解决。

posted on 2016-07-21 16:22  是个传颂厨  阅读(291)  评论(0编辑  收藏  举报