I'm trying to give context using "this" to a adapter
Code is:
val shoeid = arrayOf(
"Nike air","Adidas","asics"
)
val progress = intArrayOf(
10,50,60
)
shoeArrayList = ArrayList()
for ( i in shoeid.indices ) {
val shoe = UserShoes(shoeid[i], progress[i])
shoeArrayList.add(shoe)
}
binding.listviewProfile.adapter = ShoeAdapter(this,shoeArrayList)
Data Class:
data class UserShoes(var shoeName: String, var usage: Int)
Adapter Code:
class ShoeAdapter(private val context: Activity,private val arrayList: ArrayList<UserShoes>): ArrayAdapter<UserShoes>(context, R.layout.list_view,arrayList) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val inflater: LayoutInflater = LayoutInflater.from(context)
val view: View = inflater.inflate(R.layout.list_view, null)
val shoe: TextView = view.findViewById(R.id.shoeID)
val progress: ProgressBar = view.findViewById(R.id.progressID)
shoe.text = arrayList[position].shoeName
progress.progress = arrayList[position].usage
return super.getView(position, convertView, parent)
}
}
Type mismatch. Required: Activity
CodePudding user response:
Change
class ShoeAdapter(private val context: Activity,...
to
class ShoeAdapter(private val context: Context,...
and
binding.listviewProfile.adapter = ShoeAdapter(this,shoeArrayList)
to
context?.run { binding.listviewProfile.adapter = ShoeAdapter(this,shoeArrayList) }
You could also keep the Activity but the adapter doesn't need an Activity so it's best to go with the more abstract Context
.