Android 布局数据绑定不起作用

Android layout databinding won't work

我尝试在我的视图中动态 hide/show 一个元素,因此我遵循了这个示例

我用

我的第一个问题是错误消息 "Attribute is missing the Android namespace",但我能找到的所有示例都不提供命名空间

尽管如此,我尝试启动我的项目并遇到另一个错误:

android:visibility="@{@bool/list_show_icon ? View.VISIBLE : View.GONE}"

Error:(22, 29) No resource found that matches the given name (at 'visibility' with value '@{@bool/list_show_icon ? View.VISIBLE : View.GONE}').

看来他并没有尝试计算表达式

layout 标签内添加根 LinearLayout

<layout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 xmlns:app="http://schemas.android.com/apk/res-auto">

  <data>
     <import type="android.view.View"/>
  </data>
  <LinearLayout>
  </LinearLayout>
</layout>

使用DataBinding的第一条规则是XML的根元素必须是<layout>

<layout> 的一部分,而不是其他布局。在你的情况下应该是

<layout>
    <data> </data>
    <LinearLayout>

    </LinearLayout>
</layout>

Kishore 已经写过了。

必须是根元素并包裹整个布局 + 数据。

<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto">
  <data>
      <import type="android.view.View" />
  </data>
 <LinearLayout  
       android:layout_width="match_parent" 
       android:layout_height="match_parent"
       android:background="?android:attr/activatedBackgroundIndicator"
       android:minHeight="56dp"
       android:orientation="horizontal"
       android:paddding="8dp">
  </LinearLayout>
</layout>

无论如何,如果您使用数据绑定,我建议您使用可观察对象 Boolean/Integer 而不是在布局中使用可见性逻辑。这可以使用像

这样的 ViewModel 来解决
 <data>
     <variable name="viewModel" type="YourViewModelClass" />
 </data>

 <LinearLayout> ... <TextView android:visibility="@{viewModel.isVisible}" />
 </LinearLayout>

并在您的 ViewModel (mvvm) 中使用:

 private boolean ObservableInt isVisible = new ObservableInt(View.GONE);
 private void changeVisibility(boolean visible) { isVisible.set( visible ? View.VISIBLE : View.Gone); }

它只是更干净,但不会影响性能或其他任何东西。