在android中使用数据绑定时出错

axa*_*xay 33 data-binding android android-fragments

我想测试数据绑定的指南中给出这里.我已将其包含在我的build.gradle文件中(模块应用程序):

compileSdkVersion 'android-MNC'
buildToolsVersion '23.0.0 rc2'
Run Code Online (Sandbox Code Playgroud)

在项目build.gradle文件中,我已将其包含在我的依赖项中:

classpath "com.android.tools.build:gradle:1.3.0-beta2"
classpath "com.android.databinding:dataBinder:1.0-rc0"
Run Code Online (Sandbox Code Playgroud)

布局文件与指南中给出的文件完全相同.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
   <variable name="user" type="com.example.User"/>
</data>
<LinearLayout
   android:orientation="vertical"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <TextView android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@{user.firstName}"/>
   <TextView android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="@{user.lastName}"/>
</LinearLayout>
</layout>
Run Code Online (Sandbox Code Playgroud)

最初它给出了一个错误Element layout does not have the required attribute layout_width and layout_height.

我尝试通过为两者分配match_parent来修复它.然后我Error parsing XML: duplicate attribute在我指定的线layout_heightlayout_width线性布局上得到了错误 .

我再次试图通过删除这些属性来解决这个问题.现在,每当我尝试编译时,我都会看到 - error: package my.package.name.databinding不存在.

代码完成在我的Fragment中完美运行,我试图使用这个布局.

那么我错过了什么?

Tap*_*boy 20

您在xml文件中的绑定可能无效.

一定要仔细检查

  1. type属性是否有效引用数据对象?type="my.package.Class"
  2. 绑定是否有效?name="client"- >"@{client.field}"
  3. 数据字段是否可访问?public或用吸气剂封装
  4. 是java中的字段名称和xml文件匹配,检查拼写错误
  5. 如果已重命名xml文件,请确保还更新了Binding对象. OldNameBinding -> NewNameBinding
  6. 清洁项目

  • 这应该是公认的答案 (3认同)

小智 17

apply plugin: 'com.neenbedankt.android-apt'从我的build.gradle中删除解决了我的问题.

  • 对我来说问题是`classpath'com.neenbedankt.gradle.plugins:android-apt:1.4'升级到1.8解决了这个问题 (10认同)
  • 同样在这里,我相信数据绑定已经在内部使用了apt.如果您使用的是dagger或任何其他依赖于apt的库,只需使用提供的"com.google.dagger:dagger-compiler:2.0.1"而不是apt"com.google.dagger:dagger-compiler:2.0.1" (2认同)