Search code examples
javaandroidtextview

Set text color for multiple TextViews at once


Is there a way to set A text color for multiple textviews programmatically with one line of code (in Java/Android)?

public void MakeAllTxtWhite(){
    TextView[] alltxt = {txt1, txt2, txt3, txt4, txt5,txt6,txt7,txt8, txt9, txt10, txt11, txt12, txt13, txt14, txt15, txt16,
         txt17, txt18, txt19, txt20, txt21, txt22, txt23, txt24, txt25, txt26, txt27, txt28, txt29, txt30, txt31, txt32, txt33, txt34};
    for(TextView i : alltxt){
        i.setTextColor(i.getContext().getColor(R.color.white));
    }
}

I know it is possible to put all the txvs in a list and iterate through it, but I wonder if there is another more suitable method.


Solution

  • I would say what you are doing is fine. There is no such API to update text color of multiple TextView's. But it doesn't mean you can't extract your own helper method somewhere and use it.

    And if you wish you can avoid adding TextViews to array. For example, we can write

    public class ViewHelpers {
        public static void setTextColor(@ColorInt int colorResourceId, TextView... views) {
            for (TextView textView : views) {
                textView.setTextColor(colorResourceId);
            }
        }
    }
    

    And later in code use it as follows:

    ViewHelpers.setTextColor(R.color.myColor, textView1, textView2, textView3);