如何当按钮状态改变时改变按钮背景 [英] How to change button background when button state is changed

查看:161
本文介绍了如何当按钮状态改变时改变按钮背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道怎样才能改变我的按钮背景编程设置 onClickListener

Wondering how can I change my button background programmatically by setting onClickListener.

我的意思是,当我首次pressed我的按钮,它改变其背景图像并保存它,即使我松开手指从它。然后,如果我preSS它的第二次它必须再次更改背景图片。我知道我必须检查的背景是什么就有什么的时刻,但不明白怎么做了。

I mean that when I firstly pressed my button it changes its background image and save it even if I release finger from it. And then if i press it the second time it must change background image again. I know that I must check what background is there at the moment but can't understand how to do it.

我试过使用的getBackground 方法,但它并不适合我很有帮助。我甚至试图创建一个包含我的按钮的三态选择一个XML文件,但它只是工作,直到我松开手指从按钮的那一刻。

I've tried use getBackground method but it wasn't helpful for me. I even tried to create an XML file with selector which contains three state of my button, but it worked only until the moment I release finger from button.

推荐答案

您可以有一个全局变量存储后台INT:

You could have a global variable storing the background int:

private int backgroundNumber = 0;

然后,在的onClick(),你可以做这样的事情:

Then, in onClick() you could do something like this:

backgroundNumber++;
switch (backgroundNumber % numberOfBackgrounds) { // numberOfBackgrounds is a constant of how many backgrounds there are
    case 1: 
        button.setBackgroundResource(R.drawable.background1);
        break;
    // Do cases for all the backgrounds
}

我觉得应该工作。

I think that should work.

这篇关于如何当按钮状态改变时改变按钮背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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