如何使用数据绑定将图像URL设置为ImageView的背景?

时间:2019-02-12 05:43:04

标签: android kotlin

我已经有了一个绑定适配器,可以将来自URL的图像加载到ImageView中。现在,我需要加载背景图像URL作为图像视图的背景,并且我正在使用数据绑定,滑动以加载图像并将其写入Kotlin。

如何为该适配器编写绑定适配器?

这是我的XML

<androidx.appcompat.widget.AppCompatImageView

        android:id="@+id/ImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:adjustViewBounds="true"
        android:scaleType="centerInside"
        app:backgroundImageUrl="@{item.backgroundImageUrl}"
        app:mainImageUrl="@{item.mainImageUrl}"/>

3 个答案:

答案 0 :(得分:0)

您可以尝试如下

    try {
        ImageView i = (ImageView)findViewById(R.id.image);
        Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageUrl).getContent());
        i.setImageBitmap(bitmap);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

答案 1 :(得分:0)

尝试以下XML:

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/image_view_background"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:background="@color/colorPrimary"
        android:alpha="0.4"
        app:mainImageUrl="@{item.backgroundImageUrl}"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <ImageView
        android:id="@+id/image_view_main"
        android:layout_width="230dp"
        android:layout_height="230dp"
        app:mainImageUrl="@{item.mainImageUrl}"
        android:background="@color/colorPrimaryDark"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

</android.support.constraint.ConstraintLayout>

出于检查目的,我仅将背景图像设置为Alpha。

希望这个技巧对您有帮助。

enter image description here

答案 2 :(得分:0)

我使用了以下绑定适配器,并且工作正常。

@BindingAdapter("backgroundImageUrl")
 fun loadBackgroundImage(view: ImageView, imageUrl:String?)
{
Glide.with(view.context).load(imageUrl).into(object:SimpleTarget<Drawable>()
{
override fun onResourceReady(resource: Drawable, transition: Transition<in 
Drawable>?) 
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
 view.background = resource}
 }
 })
 }
相关问题