我用的截图做的imgView,然后toggle切换的时候前面一直有一个缩小版的图片,无法正常切换图片
main activity
package com.light.demo4;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ToggleButton;
import android.os.Build;
public class MainActivity extends ActionBarActivity implements OnCheckedChangeListener{
private ToggleButton tb;
private ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* 1、初始化toggleButton
*/
tb =(ToggleButton) findViewById(R.id.toggleButton1);
img =(ImageView) findViewById(R.id.imageView1);
/*
* 2、给当前的tb设置一个监听器
*/
tb.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
/*
* 当开关被点击时,这个方法会执行
* buttonView--代表被点击控件本身
* isChecked--代表被点击控件的状态
*
* 当点击tb的时候,更换背景
*/
img.setBackgroundResource(isChecked?R.drawable.on:R.drawable.off);
}
}
============================================================
activity_main.xml 如下:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.light.demo4.MainActivity"
tools:ignore="MergeRootFrame" >
<ToggleButton
android:checked="false"
android:id="@+id/toggleButton1"
android:textOn="开"
android:textOff="关"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<ImageView
android:layout_below="@+id/toggleButton1"
android:id="@+id/imageView1"
android:layout_marginTop="50dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/off" />
</FrameLayout>
