Button
怎么能用按钮实现点击时切换图片
怎么能用按钮实现点击时切换图片
2016-11-13
你可以参考一下下面这个代码。
//*****ToggleButton实现方法
//xml_file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="me.com.myapplication.MainActivity">
<!--添加ToggleButton-->
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:checked="false"
android:textOff="关闭"
android:textOn="打开"
android:textStyle="bold" />
<!--添加ImageView-->
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/toggleButton"
android:background="@drawable/light1" />
</RelativeLayout>
//java_file
package me.com.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.ToggleButton;
//主函数接口实现OnCheckChangeListener方法
public class MainActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
// 定义ToggleButton与ImageView对象
private ToggleButton tg_button;
private ImageView im_view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化两个对象
tg_button = (ToggleButton) findViewById(R.id.toggleButton);
im_view = (ImageView) findViewById(R.id.imageView);
// 调用ToggleButton的setOnCheckedChangeListener方法,因为是从主函数实现接口,所以可能传入this;
tg_button.setOnCheckedChangeListener(this);
}
//主函数实现了接口,需要重写onCheckChanged方法,用来实现监听到按钮状态变化所需要做处理。
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
im_view.setBackgroundResource(b ? R.drawable.light2 : R.drawable.light1);
}
}
举报