OkHttp3网络加载Bitmap到DataBinding中BindingAdapter自定义属性
定义User:
import android.databinding.BaseObservable;
import android.databinding.ObservableField;
import android.graphics.Bitmap;
public class User extends BaseObservable {
public ObservableField<Bitmap> bitmap = new ObservableField<>();
}
在XML布局中写入User:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="user"
type="com.example.fly.myapplication.User" />
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
app:userImage="@{user.bitmap}" />
</RelativeLayout>
</layout>
其中的app:userImage为自己专门为ImageView自定义的属性。下面单独为userImage属性增加绑定。Utils.java:
import android.databinding.BindingAdapter;
import android.graphics.Bitmap;
import android.widget.ImageView;
public class Utils {
@BindingAdapter({"userImage"})
public static void setImageError(ImageView imageView, Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
}
}
接着在上层Java代码使用Okhttp3加载一个网络图片到ImageView的userImage中去:
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
final User user = new User();
binding.setUser(user);
String url = "http://avatar.csdn.net/9/7/A/1_zhangphil.jpg";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
byte[] bytes = response.body().bytes();
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
user.bitmap.set(bitmap);
}
});
}
}
.gradle添加的okhttp3引用:
implementation 'com.squareup.okhttp3:okhttp:3.9.1'