Android 按钮 setColorFilter 行为 [英] Android button setColorFilter behaviour

查看:21
本文介绍了Android 按钮 setColorFilter 行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(我稍微改了一下问题,因为现在问题有点清楚了)

(I changed the question a bit, because the problem is a bit clearer now)

我的应用程序上有 4 个按钮,当用户单击某个按钮时我改变了那个按钮的颜色.

I have 4 buttons on my application, and when a user clickes certain button I change that button color.

当单击按钮 3 时,我想将他的颜色更改为绿色,否则我想删除他的绿色过滤器(单击按钮 1/2/4 时).如果我点击按钮 3 它确实得到绿色过滤器.如果然后我单击按钮 4,它会删除绿色过滤器,但如果我单击按钮 1 或 2,则没有任何反应.当我在XML中切换按钮的位置,并将button3放在第一位时,不会发生,想法?

when button 3 is clicked I want to change his color to green, otherwise I want remove his green filter (when button1/2/4 are clicked). If I click on button 3 It does get the green filter. If then I click button 4 it removes the green filter, but if I click button 1 or 2, nothing happens. When I switched the position of the buttons in the XML, and put button3 first, It doesnt happen, ideas?

layout xml的相关部分是:

The relevant part of the layout xml is:

<Button
android:id="@+id/ans1"
android:layout_width="fill_parent" 
     android:layout_height="wrap_content"/>
<Button
android:id="@+id/ans2"
android:layout_width="fill_parent" 
     android:layout_height="wrap_content" />
<Button
android:id="@+id/ans3"
android:layout_width="fill_parent" 
     android:layout_height="wrap_content" />
<Button
android:id="@+id/ans4"
android:layout_width="fill_parent" 
     android:layout_height="wrap_content" />

代码是:

if (answer.equals("3")) 
    {
        question.setText("In if");
        d.setColorFilter(filter); 
    }
    else
    {
        question.setText("else");
        d.setColorFilter(null);
    }

推荐答案

我似乎记得之前创建太多 ColorFilter 时遇到了问题.这听起来肯定不是这里的错,因为它立即发生.不过,您可能会尝试将过滤器作为类变量,然后在 if/else 块中使用它.此外,正如 Trev 提到的,由于您只想删除绿色过滤器,您可以将 null 传递给 setColorFilter 并避免制作透明过滤器,因此您最终会得到如下结果:

I seem to remember having issues when creating too many ColorFilters before. It doesn't sound for certain like that's what's at fault here, since it's happening right away. Still, what you might try is having the filter as a class variable, and then using it within the if/else block. Also, as Trev mentioned, since you're just wanting to remove the green filter, you can just pass null to setColorFilter and avoid making the transparent filter, so you'd end up with something like this:

//in main class
PorterDuffColorFilter greenFilter = 
    new PorterDuffColorFilter(Color.GREEN, PorterDuff.Mode.SRC_ATOP);

//in CheckAnswer()
Drawable d = findViewById(R.id.ans2).getBackground();

if(answer.equals("1") d.setColorFilter(greenFilter)
else d.setColorFilter(null);

这篇关于Android 按钮 setColorFilter 行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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