Search code examples
androidandroid-viewbinding

How to access child elements of a TextSwitcher using view binding?


I'm using the Android view binding to get an automatically generated binding class of my XML. In my XML definitions I'm using a TextSwitcher control with two child elements of the type TextView.

In code I access the child views of the TextSwitcher like this:

...
_binding = MyViewBinding.inflate((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE), this, true);

((TextView)_binding.myTextSwitcher.getChildAt(0)).setTextColor(_mySpecialColor);
((TextView)_binding.myTextSwitcher.getChildAt(1)).setTextColor(_mySpecialColor);
...

Is there an easier way to access the child views of the myTextSwitcher directly with the MyViewBinding class without the need to cast them?

The XML definitions looks like this:

<TextSwitcher
  android:id="@+id/myTextSwitcher"
  android:layout_width="match_parent"
  android:layout_height="wrap_content">

  <TextView
    android:id="@+id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

  <TextView
    android:id="@+id/text2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

</TextSwitcher>

Solution

  • All the time I was searching at the wrong location in the generated binding class.

    Those TextView's are there directly accessible on my _binding variable.

    // this does work
    _binding.text1.setTextColor(_headerLabelColor);
    _binding.text2.setTextColor(_headerLabelColor);
    

    I thought they need to be accessible as child's of my TextSwitcher but it seems I learned something now.

    // this does not work but I expected it to
    _binding.myTextSwitcher.text1.setTextColor(_headerLabelColor);
    _binding.myTextSwitcher.text2.setTextColor(_headerLabelColor);