Home > Mobile >  Items in RecyclerView are different with ViewBinding
Items in RecyclerView are different with ViewBinding

Time:07-15

When i make Adapter in regular way, with findViewById it looks ok: like this, but when i do it with view binding looks like this 2

Adapter with ViewBinding:

class HomePageFoldersAdapter() : RecyclerView.Adapter<HomePageFoldersAdapter.FolderHolder>() {

var list = emptyList<Folder>()
    set(value) {
        field = value
        notifyDataSetChanged()
    }

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FolderHolder {
    val inflater = LayoutInflater.from(parent.context)
    val binding = FolderHomeCardBinding.inflate(inflater)
    return FolderHolder(binding)
}

override fun onBindViewHolder(holder: FolderHolder, position: Int) {
    val folder = list[position]
    with(holder.binding) {
        val context = root.context
        nameTextView.text = folder.name
        sizeTextView.text = context.getString(R.string.modules_count, folder.modulesIds.size)
    }
}

override fun getItemCount() = list.size

class FolderHolder(val binding: FolderHomeCardBinding) : RecyclerView.ViewHolder(binding.root)

}

CodePudding user response:

try replace instead

 val binding = FolderHomeCardBinding.inflate(inflater)

with

 val binding = FolderHomeCardBinding.inflate(inflater, parent, false)

CodePudding user response:

code :

class HomePageFoldersAdapter() : RecyclerView.Adapter<HomePageFoldersAdapter.FolderHolder>() {

var list = emptyList<Folder>()
    set(value) {
        field = value
        notifyDataSetChanged()
    }

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FolderHolder {
    val inflater = LayoutInflater.from(parent.context)
    val binding = FolderHomeCardBinding.inflate(inflater, parent, false)
    return FolderHolder(binding)
}

override fun onBindViewHolder(holder: FolderHolder, position: Int) {
    val folder = list[position]
    with(holder.binding) {
        val context = root.context
        nameTextView.text = folder.name
        sizeTextView.text = context.getString(R.string.modules_count, folder.modulesIds.size)
    }
}

override fun getItemCount() = list.size

class FolderHolder(val binding: FolderHomeCardBinding) : RecyclerView.ViewHolder(binding.root)

}

Changes the XML :

android:layout_width="150dp"
android:layout_height="50dp"

  • Related