I have an annoying problem I wanted to use custom dialog in recycler view adapter but I need a context for builder and I wrote that but I can't initialized that. I looked up Internet but I can't find anything. Is anyone can help me? Thank you and have a good codes :)
private lateinit var context: Context
Adapter class
class MainAdapter(private val cityList: List<City>) : RecyclerView.Adapter<MainAdapter.ViewHolder>(){
class ViewHolder(binding: CityCardBinding):RecyclerView.ViewHolder(binding.root){
val cityBinding : CityCardBinding = binding
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = CityCardBinding.inflate(LayoutInflater.from(parent.context),parent,false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val city = cityList[position]
holder.cityBinding.cityCard = city
holder.cityBinding.cardCity.setOnClickListener {
}
}
override fun getItemCount(): Int = cityList.size
}
There are 3 ways to do it.
1. Very simple one, pass in the constructor.
You could pass the context via your adapter constructor, something like this.
In Adapter you could write:
class MyAdapter(private val context: Context) : RecyclerView.Adapter<MyAdapter.ViewHolder>() {
private lateinit var mContext: Context
fun doSomething() {
mContext = context
}
}
In your Activity/Fragment:
private fun bindAdapter() {
val adapter = MyAdapter(context = this) // Use requireActivity() for fragments
}
2. Use Dependency Injection to inject context. For example Dagger Hilt
3. You can use any view to get context.
In your case for example, holder.cityBinding.cardCity.context
this will also give you context
Suggestion:
My suggestion to you is, if anything like dialog you want to show then use activity/fragment for that, whole UI logic should be in activity/fragment to go with architecture standards.
If your requirement is Anything like you want to show particular data of one item of adapter inside dialog then on click of that button you can take a callback with your selected item data to the activity/fragment and show dialog there with data.
Hope this help!!!