【问题标题】:How to access child elements of a TextSwitcher using view binding?如何使用视图绑定访问 TextSwitcher 的子元素?
【发布时间】:2021-10-28 01:07:56
【问题描述】:

我正在使用Android view binding 来获取我的 XML 的自动生成的绑定类。在我的 XML 定义中,我使用了一个 TextSwitcher 控件和两个 TextView 类型的子元素。

在代码中,我像这样访问TextSwitcher 的子视图:

...
_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);
...

是否有更简单的方法可以直接使用 MyViewBinding 类访问 myTextSwitcher 的子视图,而无需强制转换它们?

XML 定义如下所示:

<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>

【问题讨论】:

    标签: android android-viewbinding


    【解决方案1】:

    我一直在生成的绑定类中搜索错误的位置。

    那些TextView 可以在我的_binding 变量上直接访问。

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

    我认为他们需要像我的 TextSwitcher 的孩子一样可以访问,但我现在似乎学到了一些东西。

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

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多