1

I find myself repeating the same lines of code, and I'd like to automate this a bit.

I'm doing the following to change the color of text in a view to correspond with correct/incorrect answers:

((CheckBox) findViewById(R.id.quiz_answer_2e)).setTextColor(Color.parseColor("#EE7674"));

I'd like to pass in parameters so I don't have to repeat this, I would prefer to call the function and set parameters to the function like:

public void setCorrect(String viewType, String viewName, String thisColor) {
    if (thisColor.equals("red")) {
        thisColor = "#EE7674";
    } else {
        thisColor = "#9DBF9E";
    }
    ((**viewType**) findViewById(R.id.**viewName**)).setTextColor(Color.parseColor(**thisColor**));
}

Where viewType, viewName and thisColor are passed to the method. Is there a way to do this?

I tried saving the value to a String, but couldn't determine how to get that string to run from the method.

Thanks in advance.

rweisse
  • 820
  • 10
  • 26
Erin B
  • 90
  • 9

1 Answers1

1

I would refactor your method based on the following:

  1. setTextColor(int color) is defined in TextView and is inherited by the applicable classes such as EditText, CheckBox, Button, etc.
  2. Whilst you can get a resource by its identifier (e.g. This Question) you're more likely to encounter run time errors this way. So instead I'd recommend passing the resource ID as an int
  3. At the moment you have a correct / incorrect (binary) color decision, so make the parameter a boolean with a self explanatory name such as correct and use the information to identify the color resource.

This would lead to a solution such as:

public void setCorrect(int viewId, boolean correct) {
    int colorId = correct ? R.color.correct : R.color.incorrect;
    int color = ContextCompat.getColor(getApplicationContext(), colorId);
    ((TextView) findViewById(viewId)).setTextColor(color);
}

Where the colors.xml in res/values would look something like:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="correct">#9DBF9E</color>
    <color name="incorrect">#EE7674</color>
</resources>
d.j.brown
  • 1,822
  • 1
  • 12
  • 14