Android button setColorFilter behaviour

后端 未结 5 1395
失恋的感觉
失恋的感觉 2020-12-10 09:26

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

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

相关标签:
5条回答
  • 2020-12-10 10:04

    You just need to mutate each drawable before setColorFilter.

    Drawable d = findViewById(R.id.ans2).getBackground();
    
    d = d.mutate();
    d.setColorFilter
    
    0 讨论(0)
  • 2020-12-10 10:09

    The Drawable documentation regarding setColorFilter(ColorFilter cf) states that 'null' may be passed to remove any existing filters. So, perhaps it could be that once the TRANSPARENT filter has been applied, then your subsequent GREEN filter can't be seen? I don't know enough about .setColorFilter and PorterDuff to know for sure, but it's worth a shot. Perhaps try:

    d.setColorFilter(null); 
    d.setColorFilter(filter); 
    

    Also you could instead use this method:

    setColorFilter(int color, PorterDuff.Mode mode) 
    
    0 讨论(0)
  • 2020-12-10 10:14

    Yesterday I posted a suggestion to a very similar problem that you asked here:

    Android button setColorFilter behaviour

    It appears that you have edited the code you originally posted there in order to incorporate the suggestions you were given (without acknowledging the answers) and then posted exactly the same code in this question.

    0 讨论(0)
  • 2020-12-10 10:20

    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);
    
    0 讨论(0)
  • 2020-12-10 10:23

    The default behavior when calling setColorFilter(ColorFilter) on a Drawable does not automatically invalidate the Drawable, meaning it will not redraw itself solely as a result of the method call.

    Try calling d.invalidateSelf() after setting the ColorFilter.

    0 讨论(0)
提交回复
热议问题