Akeshwar Akeshwar - 4 months ago 25
Android Question

Dynamically change the color of all TextViews in a layout file

I have a layout file with a few TextViews. I want to change the color of all of them dynamically based on a click.

Here's how I'm doing it for just one TextView:

public void openTargets() {
TextView targets = (TextView)findViewById(R.id.targets);
targets.setTextColor(ContextCompat
.getColor(getApplicationContext(),R.color.colorPrimary));
}


Doing the same thing for all the TextViews manually would be very tedious. Is it possible to reduce the code and get it done in one go?

This is how my layout file looks:

<LinearLayout
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
xmlns:android="http://schemas.android.com/apk/res/android">

<TextView
style="@style/BottomNavigation"
android:id="@+id/targets"
android:text="Targets"
android:onClick="openTargets"/>

...10 more similar TextViews following in the same LinearLayout...

Answer

Dynamically change the color of all TextViews in a layout file

Use getChildCount and getChildAt to change all TextView's color:

public void deepChangeTextColor(ViewGroup parentLayout){
    for (int count=0; count < parentLayout.getChildCount(); count++){
          View view = parentLayout.getChildAt(count);
          if(view instanceof TextView){
              ((TextView)view).setTextColor(...);
          } else if(view instanceof ViewGroup){
              deepChangeTextColor((ViewGroup)view);
          }
    }
}
Comments