【问题标题】:Can't bind a custom view无法绑定自定义视图
【发布时间】:2021-06-05 12:04:47
【问题描述】:

我正在使用自定义视图,com.deadballapp.deadball.ui.pitch.PitchLiveView,但我的绑定类无法访问此视图。绑定类能够访问 cl_pitch_live

PitchLiveView 没有膨胀,它是一个扩展 View 的类,我用它来绘制到 Canvas,所以任何绑定到自定义视图的解决方案我见过hereherehere don '似乎不适用

<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/cl_pitch_live"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/pitch_green">

        <view
            android:id="@+id/view_pitch_live"
            class="com.deadballapp.deadball.ui.pitch.PitchLiveView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/nav_header_vertical_spacing"
            android:layout_marginBottom="@dimen/btm_sheet_peek_height" />

        <include layout="@layout/bottom_sheet_pitch_live"/>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</layout>

有什么想法吗?

【问题讨论】:

  • 第一件事 view 应该是 View
  • 使用View 那么会引用View 基类吗?他们指的是自定义类,就像他们在这里做的developer.android.com/guide/topics/ui/…
  • 你可以编辑你的问题,当你尝试这个时实际发生了什么?编译时错误,运行时错误?我已经对此进行了测试,对我来说效果很好。

标签: android kotlin view binding bind


【解决方案1】:

这是在布局 xml 中定义自定义视图的替代方法。

 <com.deadballapp.deadball.ui.pitch.PitchLiveView
     android:id="@+id/view_pitch_live"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_marginTop="@dimen/nav_header_vertical_spacing"
     android:layout_marginBottom="@dimen/btm_sheet_peek_height" />

您可以使用 View Binding 或 findViewById 将其绑定为其他视图

【讨论】:

  • 你知道为什么view标签不支持数据绑定吗?
  • 我曾认为使用view 标签的这种方式可以与记事本示例中定义为内部类的自定义视图一起使用。更新了答案。只为reference
  • 当我尝试在我的示例中引用它时,它确实显示unresolved reference 数据绑定/视图绑定错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-03
  • 2018-02-21
  • 2015-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多