数据绑定:如何将 xml 中的上下文传递给方法?

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()

Jéw*_*ôm' 14

Android文档说:

context生成一个名为的特殊变量,用于根据需要在绑定表达式中使用。context 的值是Context来自根视图getContext()方法的对象。该context变量被具有该名称的显式变量声明覆盖。

所以解决方案是: android:layout_width="@{GUIUtil.getTileWidthDpInScreen(context)}


Mor*_*Koh 5

您只需要<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)

  • 不需要导入 Context,数据绑定已经将变量上下文添加到作用域中 (4认同)