Parneet Singh
05/03/2023, 3:12 PMoverride fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val obj: Color = getItem(position)!!
var resultView: View? = convertView
val viewHolder: ViewHolder
if (resultView == null) {
// as new view is to be generated. We inflate the view
resultView = LayoutInflater.from(context).inflate(R.layout.color_item, parent, false)
// TODO Implement click listener correctly and see why it give wrong position if placed in this block
// TODO instead of outside of if-else i.e it works fine outside if-else
resultView.setOnClickListener{view ->
Snackbar.make(view,"Position: $position",Snackbar.LENGTH_SHORT)
.show()
}
// creating view holder object to store the found views in the layout
viewHolder = ViewHolder()
// find the views in the layout and store the objects in the view holder class
viewHolder.colorImage = resultView.findViewById(R.id.image_view)
viewHolder.colorName = resultView.findViewById(R.id.color_title)
viewHolder.colorCode = resultView.findViewById(R.id.color_code)
resultView.tag = viewHolder
} else {
viewHolder = resultView.tag as ViewHolder
}
viewHolder.colorImage.setImageResource(R.color.white)
viewHolder.colorName.text = obj.colorName
viewHolder.colorCode.text = obj.colorCode.toString()
return resultView!!
}
can anyone tell why lateinit variable is not initialised
FYI I am calling the secondary constructor\Muhammad Utbah
05/04/2023, 7:58 AMgetView
function to initialize the ViewHolder
properties using the findViewById
method:
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val obj: Color = getItem(position)!!
var resultView: View? = convertView
val viewHolder: ViewHolder
if (resultView == null) {
// as new view is to be generated. We inflate the view
resultView = LayoutInflater.from(context).inflate(R.layout.color_item, parent, false)
// create a new ViewHolder and initialize its properties
viewHolder = ViewHolder()
viewHolder.colorImage = resultView.findViewById(R.id.image_view)
viewHolder.colorName = resultView.findViewById(R.id.color_title)
viewHolder.colorCode = resultView.findViewById(R.id.color_code)
// set the ViewHolder as the tag of the resultView
resultView.tag = viewHolder
} else {
// get the existing ViewHolder from the tag of the resultView
viewHolder = resultView.tag as ViewHolder
}
viewHolder.colorImage.setImageResource(R.color.white)
viewHolder.colorName.text = obj.colorName
viewHolder.colorCode.text = obj.colorCode.toString()
return resultView!!
}
Hope this helps!🙂