Ale*_*lex 11 android android-databinding
安卓工作室 3.0。
这是我的自定义方法:
public static int getTileWidthDpInScreen(Context context) {
// some code here
return tileWidthDp;
}
Run Code Online (Sandbox Code Playgroud)
这里是我的带有数据绑定代码的 xml 文件:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<import type="com.myproject.android.customer.util.GUIUtil" />
</data>
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageViewPhoto"
android:layout_width="@{GUIUtil.getTileWidthDpInScreen()}"
android:layout_height="@dimen/preview_image_height"
android:scaleType="centerCrop"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
</layout>
Run Code Online (Sandbox Code Playgroud)
结果我得到错误:
e: java.lang.IllegalStateException: failed to analyze: android.databinding.tool.util.LoggedErrorException: Found data binding errors.
data binding error msg:cannot find method getTileWidthDpInScreen() in class com.myproject.android.customer.util.GUIUtil
Run Code Online (Sandbox Code Playgroud)
这个错误是因为我没有在 method 中传递上下文getTileWidthDpInScreen()。
我如何获得XML上下文,并将它传递的方法:getTileWidthDpInScreen()?
您只需要<import type="android.content.Context" />在您的 xml 数据导入中导入。
然后,您可以简单地使用context.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<import type="android.content.Context" />
<import type="com.myproject.android.customer.util.GUIUtil" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/imageViewPhoto"
android:layout_width="@{GUIUtil.getTileWidthDpInScreen(context)}"
android:layout_height="@dimen/preview_image_height"
android:scaleType="centerCrop"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6344 次 |
| 最近记录: |