ImageButton的改变点击背景颜色 [英] ImageButton change background colour on click

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

问题描述

我怎样才能让我的ImageButton改变其颜色,当我点击它?

How I can make my ImageButton change its color when I click it?

我想要做这样的事情:

按钮(蓝色) - >点击 - >按钮(红色) - >点击 - >按钮(蓝色) - >点击
   - >按钮(红色)

Button(Blue) -> Click -> Button(Red) -> Click -> Button(Blue) -> Click -> Button(Red)

当我点击切换颜色,当我再次单击它可以追溯到原始的。

when I click it switch color and when I click again it goes back to original.

我试着这样做:

mTrashFlag = !mTrashFlag;
ImageButton bt = (ImageButton)findViewById(R.id.trash_button);
if(!mTrashFlag)
{
    bt.setBackgroundColor(0x4CB8FB);
}
else
{
    bt.setBackgroundColor(0xff0000);
}

但它没有工作。它改变颜色为白色,然后我不能上再次点击。

but it didnt work. It changed color to white and then I couldn't click on it again.

推荐答案

您应通过的颜色类属性,而不是六code直接:

You should pass a Color class attribute instead of the hexa code directly :

if(!mTrashFlag)
{
    bt.setBackgroundColor(Color.parseColor("#4CB8FB"));
}
else
{
    bt.setBackgroundColor(Color.RED);
}

另外,你必须注册一个<一个href=\"http://developer.android.com/reference/android/view/View.OnClickListener.htmlhttp://developer.android.com/reference/android/view/View.OnClickListener.html\"相对=nofollow> OnClickListener 上时,它的点击得到通知的按钮,所以最终code是:

Also, you have to register a OnClickListener on the button to get notified when it's clicked, so the final code is :

bt.setOnClickListener(new View.OnClickListener() {

    // 'v' is the clicked view, which in this case can only be your button
    public void onClick(View v) {
        mTrashFlag = !mTrashFlag;

        if (!mTrashFlag)
        {
            v.setBackgroundColor(Color.parseColor("#4CB8FB"));
        }
        else
        {
            v.setBackgroundColor(Color.RED);
        }
    }
});

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

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