Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android databinding src ImageView in xml

I am showing a list of include items

<include
        layout="@layout/item_tags"
         android:title='@{"text"}'
         android:image='@{"@drawable/ic_write_item.xml"}'/>

this layout contains

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable
            name="title"
            type="java.lang.String" />

        <variable
            name="image"
            type="java.lang.String" />
    </data>

...

  <ImageView...
                    android:src="@{image}"/>

                <TextView...
                    android:text="@{title}" />

also created myDatabindingAdapter

object DataBindingAdapters {

    @BindingAdapter("android:src")
    @JvmStatic
    fun setImageUri(view: ImageView, imageUri: Uri) {
        view.setImageURI(imageUri)
    }

    @BindingAdapter("android:src")
    @JvmStatic
    fun setImageDrawable(view: ImageView, drawable: Drawable) {
        view.setImageDrawable(drawable)
    }

    @BindingAdapter("android:src")
    @JvmStatic
    fun setImageResource(imageView: ImageView, resource: Int) {
        imageView.setImageResource(resource)
    }
}

and initialized in fragment this way

 val binding: FragmentTagsBinding =  DataBindingUtil.inflate(inflater,R.layout.fragment_tags, container,false)

        return binding.root

When I run it I receive the following error.

E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: @drawable/ic_write_item.xml (No such file or directory) W/ImageView: resolveUri failed on bad bitmap uri: @drawable/ic_write_item.xml

Is it a problem with the adapter? should I send the resource id instead of the file name?

Thanks for any help.

like image 861
Pablo R. Avatar asked Dec 11 '18 16:12

Pablo R.


2 Answers

My problem was declaring a variable in XML as String instead of type="android.graphics.drawable.Drawable"

also see @Janosch answer @{@drawable/ic_write_item} instead of @{"@drawable/ic_write_item.xml"}

like image 163
Pablo R. Avatar answered Sep 27 '22 17:09

Pablo R.


Android:src not gets String value. It needs a resource id (int). Additionally you can take a look at that for passing data to included layout https://medium.com/@elia.maracani/android-data-binding-passing-a-variable-to-an-include-d-layout-3567099b58f

like image 35
melianor Avatar answered Sep 27 '22 17:09

melianor