如何改变的ImageButton的点击形象? [英] how to change the image on click of imagebutton?

查看:171
本文介绍了如何改变的ImageButton的点击形象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是做一个图像按钮。我需要改变形象,当我点击图片按钮。其实它更改背景图片,但只有几秒钟。为什么?

I am make a image button .I need to change the image when I click on image button .Actually it change the background image but only for few seconds .why ?

这是我的code

 <ImageButton android:id="@+id/favorite"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:src="@drawable/start"
        android:background="#00ffffff"
        />

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
        android:drawable="@drawable/on" /> <!-- pressed -->

    <item android:drawable="@drawable/off" /> <!-- default -->
</selector>

我需要显示图片时,我点击图片按钮..?我可以写在Java方面?我可以写上的图像按钮,点击监听器?

I need to show on image when I click on image button ..? can I write on java side ? can I write on click listener of image button ?

推荐答案

这就是为什么你使用的是选择你的按钮背景,并根据按钮的状态的影像学改变。如果是pressed图像会上,并在其正常状态(pssed没有$ P $没有聚焦)的形象将是关。

That's why you are using a selector for your button background and the image changes depending on the state of the button. If it is pressed the image will be "on" and in its normal state (no pressed and no focused) the image will be "off".

编辑:

public class MainActivity extends AppCompatActivity {

ImageButton btn;
boolean isPressed;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btn = (ImageButton) findViewById(R.id.btn);
    btn.setBackgroundResource(R.drawable.normal);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(isPressed){
                v.setBackgroundResource(R.drawable.normal);
            }else{
                v.setBackgroundResource(R.drawable.pressed);
            }
            isPressed = !isPressed; // reverse
        }
    });


}


  <ImageButton
    android:id="@+id/btn"
    android:text="@string/hello_world" android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

这篇关于如何改变的ImageButton的点击形象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆