Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind viewmodel to a gridView in android?

I have a gridView in my activity with a custom adapter class, I cannot figure out how to bindview model to my activity's gridView. Here is my gridview adapter:

class ImageAdapter constructor(val mContext: Context, private val resource_layout: Int, private val images: Array<Int>) :
    ArrayAdapter<ImageAdapter.ViewHolder>(mContext, resource_layout) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        var convertView = convertView
        val holder : ViewHolder

        if(convertView == null) {
            val layoutInflater = LayoutInflater.from(mContext)
            convertView = layoutInflater.inflate(resource_layout, null)
            holder = ViewHolder()
            holder.imageItem = convertView.added_picture
            convertView.tag = holder
        } else {
            holder = convertView.tag as ViewHolder
        }

        Glide.with(mContext)
            .load("https://picsum.photos/200/300")
            .apply(RequestOptions.centerCropTransform())
            .placeholder(R.drawable.ic_add_icon)
            .into(holder.imageItem)

        return convertView!!
    }

    override fun getCount(): Int {
        return images!!.size
    }

    inner class ViewHolder {
        lateinit var imageItem : ImageView
    }
}
like image 287
SuvodipMondal Avatar asked Dec 10 '25 14:12

SuvodipMondal


1 Answers

Take <layout></layout> inside your row file and you can set the variable name of your ViewModel name. Now you can set inflate your view in your getViewHolder in adapter as like below.

mTaskCustomLayoutBinding =
            DataBindingUtil.inflate(inflater, R.layout.task_custom_layout, parent, false)
        return MyViewHolder(this!!.mTaskCustomLayoutBinding!!)

Set binding in your viewholder class

inner class MyViewHolder(val mBinding: TaskCustomLayoutBinding) :
        RecyclerView.ViewHolder(mBinding.getRoot())

So, you'll get the object of the binding and set the the data to your views.

Hope It'll help you :)

like image 84
Komal Avatar answered Dec 12 '25 02:12

Komal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!