相关疑难解决方法(0)

使用Android中的数据绑定在ImageView的android:src中设置可绘制资源ID

我正在尝试使用数据绑定将drawable资源ID设置为ImageView的android:src

这是我的对象:

public class Recipe implements Parcelable {
    public final int imageResource; // resource ID (e.g. R.drawable.some_image)
    public final String title;
    // ...

    public Recipe(int imageResource, String title /* ... */) {
        this.imageResource = imageResource;
        this.title = title;
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

这是我的布局:

<?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">

    <data>
        <variable
            name="recipe"
            type="com.example.android.fivewaystocookeggs.Recipe" />
    </data>

    <!-- ... -->

    <ImageView
        android:id="@+id/recipe_image_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:scaleType="centerCrop"
        android:src="@{recipe.imageResource}" />

    <!-- ... -->

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

最后,活动类:

// ...

public class RecipeActivity extends AppCompatActivity {

    public static …
Run Code Online (Sandbox Code Playgroud)

android android-layout android-databinding

72
推荐指数
8
解决办法
5万
查看次数