简体   繁体   中英

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
    }
}

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 :)

GridView grid = (GridView) itemView.findViewById(R.id.mGridView);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM