在 android.widget.ImageView 上找不到参数类型为 int 的属性'android:layout_width'的设置器



app/build.gradle中:

dataBinding {
        enabled = true
}
kapt "com.android.databinding:compiler:3.0.1"

在布局中,我有两个图像。

我想为第一个图像设置宽度

这是XML布局:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <import type="com.myproject.android.customer.util.GuiUtil" />
    </data>
            <ImageView
            android:id="@+id/imageViewPhoto"
            android:layout_width="@{GuiUtil.getTileWidthDpInScreen(context), default=@dimen/preview_image_height}"
            android:layout_height="@dimen/preview_image_height"/>
            <ImageView
            android:id="@+id/imageViewFavorite"
            android:layout_width="28dp"
            android:layout_height="28dp"/>    
</layout>

这是适配器的代码:

    @BindingAdapter("layout_width")
    public static void setLayoutWidth(View view, int width) {
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.width = width;
        view.setLayoutParams(layoutParams);
}

这是方法GuiUtil.getTileWidthDpInScreen

public class GuiUtil {    
    public static int getTileWidthDpInScreen(Context context) {
        // some logic that return int value
   }

但是我得到了这个错误:

:app:transformDataBindingWithDataBindingMergeArtifactsForDebug UP-TO-DATE
:app:kaptDebugKotlin
e: java.lang.IllegalStateException: failed to analyze: android.databinding.tool.util.LoggedErrorException: Found data binding errors.
****/ data binding error ****msg:Cannot find the setter for attribute 'android:layout_width' with parameter type int on android.widget.ImageView.
file:myprojectappsrcmainreslayoutpreview_offer_item.xml
loc:26:36 - 26:74
**** data binding error ****    
    at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:57)

不幸的是,默认情况下,该语法不支持Android数据链接。您可以改用@BindingAdapter,以下是下面的完整代码(kotlin):

    @BindingAdapter("layoutWidth")
fun setLayoutWidth(layout: ViewGroup, dimen: Float) {
    val layoutParams = layout.layoutParams
    layoutParams.width = dimen.toInt()
    layout.layoutParams = layoutParams
}

在您的XML布局文件中使用" app:layoutwidth",即使使用其他语法,例如:

,也可以使用它。
android:layout_width="match_parent"   //required
android:layout_height="@dimen/dp_102"   //required
app:layoutWidth="@{variable.predict ? @dimen/dp_86 : @dimen/dp_102}"            

在您的xml中,应该像这个

app:layout_width="@{GuiUtil.getTileWidthDpInScreen(context), default=wrap_content}"

尝试将其用于bindingadapter:

@BindingAdapter("android:layout_width")

adding:app:布局中的布局宽度,所需值适合我:喜欢:

android:layout_width="wrap_content"   
android:layout_height="wrap_content"   
app:layoutWidth="@{testBoolean == true ? @dimen/value_1 : @dimen/value_2}"   

最新更新