Search code examples
javaandroidcolorstextviewbutterknife

Butterknife @BindColor : How to pass param to method and set TextView Color?


Am I doing anything wrong ? I need to pass the integer variables that I have to the switch.

This works (with numbers):

@BindColor(R.color.white) protected int white;
@BindColor(R.color.black) protected int black;

Passing int value as number

setTextColor(1);

Then, treat at switch:

private void setTextColor(int color){
        switch (color){
            case 1 : {
                textViewUserName.setTextColor(black);
                textViewCardNumber.setTextColor(black);
                break;
            }
            case 2 : {
                textViewUserName.setTextColor(white);
                textViewCardNumber.setTextColor(white);
                break;
            }
        }
    }

But when I pass the int white or black value, the switch doesn't work. Why?

setTextColor(white);

Now switch the id's

private void setTextColor(int color){
        switch (color){
            case R.color.black : {
                textViewUserName.setTextColor(black);
                textViewCardNumber.setTextColor(black);
                break;
            }
            case R.color.white: {
                textViewUserName.setTextColor(white);
                textViewCardNumber.setTextColor(white);
                break;
            }
        }
    }

Nothing happens, no changes at textView color.


Solution

  • You are just mixing up 2 completely different things : colors and ids.

    R.color.black is the id of a color you created in a resource file like this #ff000000

    black as resolved by your BindColor (or getResources().getColor(R.color.black) in your own response) is the integer with the value equal to 0xff000000 which is -16777216

    So in your second switch you are passing a color and compare it with ids and then it's expected that you don't enter any cases of the switch.

    By the way this switch is completely unnecessary as all you were doing inside is using the value twice (just use color), but if you really wanted to use a switch you should use black and white as cases and not R.id.white and R.id.black given the input you provided to your function