通过绑定kotlin在recycleview中加载毕加索的图像



我想使用databinding通过Picassorecycler view中加载图像,但当我不知道如何在recycler viewdata class中使用@BindingAdapter时。我知道它在java中是如何工作的,但在kotlin中我不知道如何使用它。这是适配器的数据类:

data class Users(val name: String,
val email: String,
val img_link: String)

这是适配器:

class AdapterRecPart02(private val context: Context, private val ls: List<Users>) :
RecyclerView.Adapter<AdapterRecPart02.ItemAdapter>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemAdapter {
val inflater = LayoutInflater.from(context)
val binding: LayoutRecPart02Binding =
DataBindingUtil.inflate(inflater, R.layout.layout_rec_part02, parent, false)
return ItemAdapter(binding)
}
override fun onBindViewHolder(holder: ItemAdapter, position: Int) {
holder.bind(ls[position])
}
override fun getItemCount(): Int = ls.size

inner class ItemAdapter(private val bindingAdapter: LayoutRecPart02Binding) :
RecyclerView.ViewHolder(bindingAdapter.root) {
fun bind(user: Users) {
bindingAdapter.users = user
bindingAdapter.executePendingBindings()
}

}

}

这是适配器的自定义布局:

<?xml version="1.0" encoding="utf-8"?>
<data>
<variable
name="users"
type="ir.xs.mvvm.model.Users" />
</data>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/img_user"
android:layout_width="120dp"
android:layout_height="120dp" />
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/img_user"
android:text="@{users.name, default = name}"
android:textSize="16sp" />
<TextView
android:id="@+id/tv_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tv_name"
android:layout_marginTop="16dp"
android:layout_toRightOf="@+id/img_user"
android:text="@{users.email, default = email}"
android:textSize="16sp" />
</RelativeLayout>

下面是一个简单的绑定适配器,它将使用Picasso来加载图像:

@BindingAdapter("urlImage")
fun bindUrlImage(view: ImageView, imageUrl: String?) {
if (imageUrl != null) {
Picasso.get()
.load(imageUrl)
.fit()
.centerCrop()
.into(view)
} else {
view.setImageBitmap(null)
}
}

在数据绑定布局中如何使用此绑定适配器:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:binding="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">


<data>
<variable
name="imageUrl"
type="String" />

</data>


//.......


<androidx.appcompat.widget.AppCompatImageView
android:id="@+id/myImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
binding:urlImage="@{ imageUrl }" />

</layout>

对于问题中的特定情况,您将如何绑定图像url:

<ImageView
android:id="@+id/img_user"
android:layout_width="120dp"
android:layout_height="120dp"
binding:urlImage="@{ users.img_link }" />

最新更新