DataBinding 图片
[TOC]
步骤
加载一张网络图片
1. Bean中添加图片路径
ImgBean.bean
@BindingAdapter("imgPath")
:添加反射,进行控件绑定,imgPath
:为属性名
@BindingAdapter
注解的方法必须为静态方法
public class ImgBean {
private String imgUrl;
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getImgUrl() {
return imgUrl;
}
@BindingAdapter("imgPath")
public static void getImg(ImageView iv, String imgUrl) {
Picasso.with(iv.getContext()).load(imgUrl).into(iv);
}
}
2. 与控件进行绑定
img_activity.xm
引入空间:
xmlns:app="http://schemas.android.com/apk/res-auto"
绑定:
app:imgPath
<?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="imgBean"
type="com.img.ImgBean"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:imgPath="@{imgBean.imgUrl}"/>
</LinearLayout>
</layout>
3. 数据绑定
ImgActivity.java
public class ImgActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImgActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.img_activity);
ImgBean imgBean = new ImgBean();
imgBean.setImgUrl("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png");
binding.setImgBean(imgBean);
}
}
至此,运行我们的app,即可看到对应的效果,当然,因为要通过网络获取图片,所以不要忘了添加网络访问权限!