Android数据绑定 - '找不到属性的资源标识符'

mar*_*dan 33 data-binding android

我的布局文件:

<RelativeLayout 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"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".MainActivity">

<TextView
      android:text="@string/hello_world"
      android:layout_width="wrap_content"
      app:fontName="Roboto-Regular.ttf"
      android:layout_height="wrap_content"/>

</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

我的绑定适配器方法:

public class FontBinding {

  @BindingAdapter("bind:fontName")
  public static void setFontName(TextView view, @NonNull String fontName) {
    String fontPath = "/fonts/" + fontName;

    Typeface typeface = Typeface.createFromAsset(view.getContext().getAssets(), fontPath);

    view.setTypeface(typeface);
  }
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误:

Error:(8) No resource identifier found for attribute 'fontName' in package 'com.example.databindingproject'
Run Code Online (Sandbox Code Playgroud)

按照https://developer.android.com/tools/data-binding/guide.html中的教程进行操作.我可能做错了什么想法?

Geo*_*unt 65

您必须使用数据绑定语法.它应该是:

<TextView
      android:text="@string/hello_world"
      android:layout_width="wrap_content"
      app:fontName='@{"Roboto-Regular.ttf"}'
      android:layout_height="wrap_content"/>
Run Code Online (Sandbox Code Playgroud)

  • 您必须使用数据绑定布局.根标记必须是<layout>,否则数据绑定系统将不知道它应该解析您的布局文件. (8认同)
  • 您必须使用DataBinding进行充气.在onCreate中,使用`DataBindingUtil.setContentView(this,R.layout.activity_main)`而不是`setContentView(R.layout.activity_main)` (3认同)

Wol*_*ang 12

如果忘记结束大括号,也会发生同样的错误:

android:text="@{viewModel.foo"
Run Code Online (Sandbox Code Playgroud)