How to bind view from constructor in ViewHolder? - android

Could you please help me to bind views in view holder. I have read existing answer but not sure how to implement it in my case.
My holder looks like this and I don't have onCreateViewHolder
class MyViewHolder(
itemView: View,
private val myListener: MyListener
) : RecyclerView.ViewHolder(itemView) {
private val myLabel: AppCompatTextView = itemView.**findViewById**(R.id.myLabel)//**here need to remove findviewbyId**
fun bindView() {
itemView.background = ContextCompat.getDrawable(itemView.context, R.drawable.image)
myLabel.setOnClickListener {
myListener.myMethod()
}
}
}

Pretty close, what you are missing is the binding in the constructor
class MyViewHolder(
private val binding: YourLayoutBinding, //you can access it because is private val
...
) : RecyclerView.ViewHolder(binding.root) { //You need the view so pass the root view of the binding
//change your view to binding dot view
fun bindView() {
binding.background = ContextCompat.getDrawable(itemView.context, R.drawable.image) //in this case the background seems data binding so I'm treating it as such
binding.myLabel.setOnClickListener {
myListener.myMethod()
} //but here myLabel is a view contained inside the binding
}
}
And you are probably gonna have doubts regarding the onCreateViwHolder
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = YourLayoutBinding.inflate(inflater, parent, false)
return MyViewHolder(binding, ...)
}
The trick is the bindings have an static method to inflate them

Related

Use of binding breaks RecyclerView item layout

I am building an Android app with Kotlin and decided to replace the calls to findViewById and use binding. It all works fine but specifically, when I change an Adapter for a RecyclerView it breaks the item layout.
Original code with findViewById:
class WeightListAdapter(val weights: List<WeightWithPictures>, val onWeightItemClickListener: OnWeightItemClickListener) : RecyclerView.Adapter<WeightListAdapter.WeightHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WeightListAdapter.WeightHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item_weight, parent, false)
return WeightHolder(view)
}
override fun onBindViewHolder(holder: WeightListAdapter.WeightHolder, position: Int) {
val weightWithPictures = weights[position]
holder.bind(weightWithPictures)
}
override fun getItemCount() = weights.size
inner class WeightHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
private lateinit var weight: Weight
private val weightValueView: TextView = this.itemView.findViewById(R.id.weightValue)
private val weightDateView: TextView = this.itemView.findViewById(R.id.weightDate)
private val weightImageView: ImageView = this.itemView.findViewById(R.id.weightImage) as ImageView
And this is the layout:
But then whenever I use binding:
class WeightListAdapter(val weights: List<WeightWithPictures>, val onWeightItemClickListener: OnWeightItemClickListener) : RecyclerView.Adapter<WeightListAdapter.WeightHolder>() {
private var _binding: ListItemWeightBinding? = null
private val binding get() = _binding!!
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WeightListAdapter.WeightHolder {
_binding = ListItemWeightBinding.inflate(LayoutInflater.from(parent.context))
val view = binding.root
return WeightHolder(view)
}
override fun onBindViewHolder(holder: WeightListAdapter.WeightHolder, position: Int) {
val weightWithPictures = weights[position]
holder.bind(weightWithPictures)
}
override fun getItemCount() = weights.size
inner class WeightHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
private lateinit var weight: Weight
private val weightValueView: TextView = binding.weightValue
private val weightDateView: TextView = binding.weightDate
private val weightImageView: ImageView = binding.weightImage
The layout breaks:
Any ideas about what am I doing wrong here? Is it a bug?
P.S - For now, I am just adding the annotation to ignore bindings as documented here for the item view but I would really like to understand what's wrong.
Your binding needs to be inflated in the context of its parent so its root view's layout params will take effect:
binding = ListItemWeightBinding.inflate(LayoutInflater.from(parent.context), parent, false)
I think it will also give you problems that you are creating a binding property for the Adapter if you try to use it long term. Each ViewHolder holds a distinct view with a distinct binding instance. It's working now because you use it only for the ViewHolder instantiation immediately after setting each instance. But if that's all your intent is, you should just pass the binding to the constructor of your ViewHolder and omit the adapter's property.
By the way, this is the sort of pattern I use for ViewHolders. Less code. Note, it doesn't have to be an inner class.
class WeightHolder(binding: ListItemWeightBinding) : RecyclerView.ViewHolder(binding.root), View.OnClickListener {
fun bind(item: WeightWithPictures) {
with (binding) {
// set data for views here
}
}
}
I agree with #Tenfour04, using the same instance of binding is wrong but I believe the root cause of your issue is with the binding logic. with binding, the data is bound to bind with the view but not immediately. So your view gets inflated but since the binding happens at a later stage, scheduled to happen in near future, the item_view width is shrunk.
So try the following,
// oncreate view logic
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WeightListAdapter.WeightHolder {
val binding = ListItemWeightBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return WeightHolder(binding)
}
// onBindViewHolder logic remains the same
// this remains same as suggested by #Tenfour04 but a change in the bind function
class WeightHolder(binding: ListItemWeightBinding) : RecyclerView.ViewHolder(binding.root), View.OnClickListener {
fun bind(item: WeightWithPictures) {
with (binding) {
// set data for views using databindig
customVariable = item
executePendingBindings() // this is important
}
}
}
// define the customvariable in your `item_list_view.xml`
<variable
name="customVariable"
type="packagename.WeightWithPictures" />
executePendingBindings() is the way we force the binding to happen right away and not to schedule it later
Edit:
This answer is from Databinding perspective and not ViewBinding

android - Creating and using ViewBinder inside a RecyclerView adapter

In my app, there is an Activity which has a RecyclerView inside, which loads the list of options needed for that screen.
In the code below, i tried to implement a binder, which is needed because of the recent Android changes.
However, when i open the activity starts, the application crashes, throwing this error, linking the line with binding = ItemSettingsBinding.bind(binding.root):
kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized
What am i doing wrong? What's the correct way to implement a binder inside an adapter?
AdapterSettings.kt
class AdapterSettings(
var settingsList: List<DataItemSettings>,
var listener: OnItemClickListener
) : RecyclerView.Adapter<AdapterSettings.SettingsViewHolder>() {
private lateinit var binding: ItemSettingsBinding
inner class SettingsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
init {
itemView.setOnClickListener(this)
}
override fun onClick(p0: View?) {
val position : Int = adapterPosition
if (position != RecyclerView.NO_POSITION) {
listener.OnItemClick(position)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SettingsViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_settings, parent, false)
return SettingsViewHolder(view)
}
override fun getItemCount(): Int {
return settingsList.size
}
override fun onBindViewHolder(holder: SettingsViewHolder, position: Int) {
binding = ItemSettingsBinding.bind(binding.root)
holder.itemView.apply {
binding.rvTitle.text = settingsList[position].stringTitle
binding.rvDescription.text = settingsList[position].stringDescription
binding.rvIcon.setImageResource(settingsList[position].itemIcon)
}
}
interface OnItemClickListener {
fun OnItemClick(position: Int)
}
}
I believe you're missing your inflate in onCreateViewHolder:
// Pseudo-Code
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SettingsViewHolder {
val binding = ItemSettingsBinding
.inflate(LayoutInflater.from(parent.context), parent, false)
return SettingsViewHolder(binding)
}
Then you can make use of it.
Create the binding in onCreateViewHolder and pass the binding into the ViewHolder instead of the inflated View. Thus you create a binding for each created view and only need to do the apply stuff in the onBindViewHolder
Example:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SettingsViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_settings, parent, false)
val binding = ItemSettingsBinding.bind(view)
return SettingsViewHolder(binding)
}
override fun onBindViewHolder(holder: SettingsViewHolder, position: Int) {
holder.binding.apply {
rvTitle.text = settingsList[position].stringTitle
rvDescription.text = settingsList[position].stringDescription
rvIcon.setImageResource(settingsList[position].itemIcon)
}
}
Adapt your ViewHolder accordingly
There is indeed another way to ViewBind in an adapter.
First, we need to setup the ViewHolder in a different way:
inner class SettingsViewHolder(private val binding: ItemSettingsBinding):
RecyclerView.ViewHolder(binding.root), View.OnClickListener {
With this, we created a binding value inside the brackets, so we are able to call the items of the actual view or layout trough binding.root
Inside the viewholder, we need to create a function used to bind our items. We can either bind like this:
fun bind(item: Item) {
binding.item = item
binding.executePendingBindings()
}
Or like this:
fun bind(item: DataItemSettings) {
binding.rvTitle.text = settingsList[position].stringTitle
binding.rvDescription.text = settingsList[position].stringDescription
binding.rvIcon.setImageResource(settingsList[position].itemIcon)
}
NOTICE: 'getter for position: Int' is deprecated. Deprecated in Java.
And, final step, we need to write this, inside bindViewHolder:
override fun onBindViewHolder(holder: SettingsViewHolder, position: Int) {
holder.bind(settingsList[position])
}

how to get Checkbox isChecked data from recyclerview in Kotlin

I want to get isChecked data from checkbox from recycler view in this I am using Binding Adapter but I am not getting how to do that. If anyone has a way to do that then please share it.
class ItemListAdapter(private val itemDeleteListener: ItemDeleteListener,
private val checkItemListener: CheckItemListener) :
ListAdapter<ListItemTable, ItemListAdapter.ViewHolder>(ListItemDiffCallBack()) {
class ViewHolder(private val binding: ShowItemBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(listItemTable: ListItemTable, itemDeleteListener: ItemDeleteListener,
checkItemListener: CheckItemListener) {
binding.itemHistory = listItemTable
binding.itemDelete = itemDeleteListener
binding.checkItem = checkItemListener
binding.executePendingBindings()
}
companion object {
fun from(parent: ViewGroup): ViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding = ShowItemBinding.inflate(layoutInflater, parent, false)
return ViewHolder(binding)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder.from(parent)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(getItem(position), itemDeleteListener, checkItemListener)
getItem(position).itemCompleted
}
class ItemDeleteListener(val clickListener: (listId: Long) -> Unit) {
fun onClick(listItemTable: ListItemTable) = clickListener(listItemTable.itemId)
}
class CheckItemListener(val clickListener: (listId: Long) -> Unit){
fun onClick(listItemTable: ListItemTable) = clickListener(listItemTable.itemId)
}
class ListItemDiffCallBack : DiffUtil.ItemCallback<ListItemTable>() {
override fun areItemsTheSame(oldItem: ListItemTable, newItem: ListItemTable): Boolean {
return oldItem.itemId == newItem.itemId
}
override fun areContentsTheSame(oldItem: ListItemTable, newItem: ListItemTable): Boolean {
return oldItem == newItem
}
}
}
See: https://developer.android.com/topic/libraries/data-binding/two-way
If you're using data binding I think you should take a look at two-way data binding. It's even introduced through this checkbox problem inside the docs, so you're in luck!
Edit: To be a bit more specific you would implement this like so:
Create a binding adapter that sets the property on the view
<layout>
<data>
<variable
name="itemHistory"
type="your.package.ListItemTable" />
<variable
name="checkItem"
type="android.widget.CompoundButton.OnCheckedChangeListener" />
<!-...->
</data>
<CheckBox
android:id="#+id/rememberMeCheckBox"
android:checked="#{itemHistory.itemCompleted}"
android:onCheckedChanged="#{checkItem}"
/>
</layout>
So you have to use OnCheckedChangeListener instead of your own listener, and pass that to your xml.
You already have 2 "listeners" on your constructor of the adapter and you are passing them to the view holder by using the bind method.
class ItemListAdapter(private val itemDeleteListener: ItemDeleteListener, private val checkItemListener: CheckItemListener)
So you have to pass the correct one to your view holder and then set the checkbox listener. Is better to use the constructor of the view holder to avoid passing the same listener on every binding
class ViewHolder(private val binding: ShowItemBinding, private val itemDeleteListener: ItemDeleteListener, private val checkItemListener: CheckItemListener) {
fun bind(listItemTable: ListItemTable) {
binding.YOUR_CHECKBOX.setOnCheckedChangeListener(null)
binding.itemHistory = listItemTable
binding.itemDelete = itemDeleteListener
binding.checkItem = checkItemListener
binding.executePendingBindings()
binding.YOUR_CHECKBOX.setOnCheckedChangeListener { -, isChecked ->
//here call your "listener" by example
checkItemListener.theMethod(isChecked)
}
}
}
We set the checkbox listener to null first so we can stop listening and then set the view values, otherwise, anything changing the view will also trigger the listener, once the view values are set, then set the checkbox listener to trigger the callbacks.

Why does my code not enter this adapter class?

I'm new to Kotlin and Android studio.
I'm trying to get a recycle view to work properly but I'm running into a problem when trying to use an adapter class.
I tried taking a look with breakpoints. but it seems to trigger on the very first line where the class gets defined. ( so class OrganisationsAdapter...etc ) and after that it skips the whole class, it doesnt even enter it.
I also don't get any exceptions.
Adapter Class
class OrganisationsAdapter(
private val myDataset: Array<String>
) : RecyclerView.Adapter<OrganisationsAdapter.MyViewHolder>() {
class MyViewHolder(
val textView: TextView
) : RecyclerView.ViewHolder(textView) {
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
var cell = LayoutInflater.from(parent.context).inflate(R.layout.example_item, parent, false)
val textView = cell.findViewById<TextView>(R.id.organisation_name)
return MyViewHolder(textView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.textView.text = myDataset[position]
}
override fun getItemCount() = myDataset.size
}
**The line I use to call the class **
recyclerViewOrganisationFragment.adapter = OrganisationsAdapter(Array(getTopics().size) { i -> getTopics()[i].name })
You need to pass the inflated layout to ViewHolder instead of TextView
ex:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
var cell = LayoutInflater.from(parent.context).inflate(R.layout.example_item, parent, false)
return MyViewHolder(cell)
}
class MyViewHolder(
val itemView: View
) : RecyclerView.ViewHolder(itemView) {
//TODO get textview here itemView.findViewByID
}
Update the viewholder accordingly with textview etc.,
Thank you Lakhwinder.
"You need to pass on ArrayList on the constructor of the adapter, you are passing a size"

Kotlin: Passing data/array from Recyclerview Activity to Adapter

I am trying to pass an array from my Recyclerview Activity to its Adapter as such:
//Setting NavBar Title
val navBarTitle = intent.getStringExtra(FirstCustomViewHolder.LESSON_TITLE_KEY)
supportActionBar?.title = navBarTitle
var content : Array<String>
if (navBarTitle == "Introduction"){
content = arrayOf("Intro1", "Intro2")
}
else{
content = arrayOf(":esson1-1", "Lesson 1-2")
}
I am passing the array as such:
recyclerView_main.adapter = SecondAdapter(content)
And I am getting an angry red underline as shown below.
On mouse-over the pop-up error reads:
Too many arguments for public constructor......
Is there a proper way to pass an array or variable to my adapter? I am fairly new to Kotlin and appreciate and pointers.
Thank you.
Edit:
As requested, this is my adapter class:
class SecondAdapter : RecyclerView.Adapter<SecondCustomViewGolder>(){
//Variable below to be replaced by array from Activity
var lessons = arrayOf("Satu", "Dua", "Tiga", "Empat", "Lima", "Enam", "Tujuh",
"Lapan", "Sembilan")
override fun getItemCount(): Int {
return lessons.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SecondCustomViewGolder {
var layoutInflater = LayoutInflater.from(parent.context)
var cellForRow = layoutInflater.inflate(R.layout.lesson_row, parent, false)
return SecondCustomViewGolder(cellForRow)
}
override fun onBindViewHolder(holder: SecondCustomViewGolder, position: Int) {
}
}
class SecondCustomViewGolder(var viewTwo : View) : RecyclerView.ViewHolder(viewTwo){
}
Does your SecondAdapter class constructor accept an Array as an argument? If not, you must add it there. The error is because you're trying to pass an argument to a constructor that accepts no arguments.
EDIT
Do it like so:
class SecondAdapter(val lessonArray: Array<String>) : RecyclerView.Adapter<SecondCustomViewGolder>(){
override fun getItemCount(): Int {
return lessons.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SecondCustomViewGolder {
var layoutInflater = LayoutInflater.from(parent.context)
var cellForRow = layoutInflater.inflate(R.layout.lesson_row, parent, false)
return SecondCustomViewGolder(cellForRow)
}
override fun onBindViewHolder(holder: SecondCustomViewGolder, position: Int) {
}
}
class SecondCustomViewGolder(var viewTwo : View) : RecyclerView.ViewHolder(viewTwo){
}
I made it a val since it's my preference. If you intend to modify the variable, than you just declare it as a var in the constructor. There's no need to assign it inside the class. Just declaring it in the constructor makes it accessible throughout the class.
You can use the ListAdapter
and use submitList()

Categories

Resources