Updated 15 December 2016
Earlier we saw how to bind the text with layout in android, but what about image as generally all the image related android attributes deal with Bitmap of image while from server/ network we only get URI (or you can say URLs). So how go we map a imageview withe our image.
case-1: Transfer bitmap over network
But its the waste of users data and network channel as its way to much heavy and a single request can contain more than dozens of images. Moreover many of the images send by network is not even used. So its a bad idea!
case-2: Make a custom attribute and load the image in it.
And that will probably be the best way to bind your image as now you can bind them to the urls and also its really easy and you can do this without changing whatever library you were using earlier for the image loading. So I will show you two examples one with picasso and other with volley Image Loader.
First: Picasso
Create a class with any name, as i did ImageBinder.java now create your attribute in it
1 2 3 4 5 6 7 |
@BindingAdapter("imageUrl") public static void setImageUrl(ImageView view, String imageUrl) { Picasso.with(view.getContext()) .load(imageUrl) .placeholder(R.drawable.placeholder) .into(view); 0)); } |
And just pass your URI/URL to the layout as
1 2 3 4 5 6 7 8 9 10 11 12 |
<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <data> <variable name="prod" type="com.webkul.example.Product"/> </data> <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" app:imageUrl="@{prod.img_url}"/> </layout> |
Second: Volley
The layout will be same just the method implementation will be changed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@BindingAdapter("imageUrl") public static void setImageUrl(ImageView view, String imageUrl) { Context context = view.getContext(); RequestQueue mRequestQueue= Volley.newRequestQueue(this.getApplicationContext()); ImageLoader mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() { private final LruCache<String, Bitmap> cache = new LruCache<>(20); @Override public Bitmap getBitmap(String url) { return cache.get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { cache.put(url, bitmap); } }); mImageLoader.get(imageUrl, ImageLoader.getImageListener(view, 0, 0)); } |
As you can see its quiet easy and can implement any method you want to add your images. So start binding your data in android.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
3 comments