我正在尝试使用数据绑定将可绘制资源 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;
}
// ...
}
这是我的布局:
<?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>
最后,活动课:
// ...
public class RecipeActivity extends AppCompatActivity {
public static final String RECIPE_PARCELABLE = "recipe_parcelable";
private Recipe mRecipe;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRecipe = getIntent().getParcelableExtra(RECIPE_PARCELABLE);
ActivityRecipeBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_recipe);
binding.setRecipe(mRecipe);
}
// ...
}
它根本不显示图像。我究竟做错了什么?
顺便说一句,它与标准方式完美配合:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe);
final ImageView recipeImageView = (ImageView) findViewById(R.id.recipe_image_view);
recipeImageView.setImageResource(mRecipe.imageResource);
}
原文由 Yuriy Seredyuk 发布,翻译遵循 CC BY-SA 4.0 许可协议
截至 2016 年 11 月 10 日的答复
下面 Splash 的评论强调没有必要使用自定义属性类型(如
imageResource
),我们可以为android:src
创建多个方法,如下所示:旧答案
您总是可以尝试使用适配器:
然后你可以像这样在你的xml中使用适配器
请务必注意 xml 中的名称与 BindingAdapter 注释 (imageResource) 匹配
DataBindingAdapters 类不需要在任何地方特别声明,DataBinding 机制会发现它无论如何(我相信)