I'm a beginner here and I'm struggling to find a good explanation on how to make an onClickListener, I don't want to copy, I want to understand everything, as I'm already working hard on understanding the process of creating recyclerView
I am currently trying to create a Quiz application with levels. My recyclerView has a number of "cardViews" that represent each level. Basically, I want people to click on the first level, for example, to access a new activity (the game activity). And each of my levels will be directed to a game activity when they click on it. But I really don't understand how to do this simple thing... Thanks!
Here is my HomeActivity, my AdapterLvl and Data Class:
class HomeActivity : AppCompatActivity() {
lateinit var listLvl: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
listLvl = findViewById<RecyclerView>(R.id.listLvl)
val items = listOf(
Lvl("First LVL", R.drawable.background_color),
Lvl("Second LVL", R.drawable.background_color2),
Lvl("Third LVL", R.drawable.background_color),
Lvl("Fourth LVL", R.drawable.background_color2),
Lvl("Fifth LVL", R.drawable.background_color),
Lvl("Sixth LVL", R.drawable.background_color2),
Lvl("Seventh LVL", R.drawable.background_color),
Lvl("Eighth LVL", R.drawable.background_color2),
Lvl("Ninth LVL", R.drawable.background_color),
Lvl("Tenth LVL", R.drawable.background_color2),
)
listLvl.apply {
layoutManager = LinearLayoutManager(this@HomeActivity)
adapter = LvlAdapter(items)
}
}
}
class LvlAdapter(var items: List<Lvl>) : RecyclerView.Adapter<LvlAdapter.LvlViewHolder>() {
val limit = 10;
inner class LvlViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var titleLvl: TextView
var buttonLvl: ImageView
init {
titleLvl = itemView.findViewById(R.id.titleLvl)
buttonLvl = itemView.findViewById(R.id.buttonLvl)
}
fun bind(lvl: Lvl) {
titleLvl.text = lvl.title
buttonLvl.setImageResource(lvl.button)
}
}
// return the viewHolder with the item view, but inflate from xml to view first
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LvlViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.lvl_card, parent, false)
return LvlViewHolder(itemView)
}
// what we bind in the viewHolder (ce qu'on injecte)
override fun onBindViewHolder(holder: LvlViewHolder, position: Int) {
var lvl = items[position]
holder.bind(lvl)
}
// return a size of the items
override fun getItemCount(): Int {
if(items.size > limit){
return limit
} else {
return items.size
}
} }
data class Lvl(
var title : String,
var button : Int
)