Simple Android RecyclerView example

前端 未结 11 1425
名媛妹妹
名媛妹妹 2020-11-22 02:03

I\'ve made a list of items a few times using Android\'s RecyclerView, but it is a rather complicated process. Going through one of the numerous tutorials online

11条回答
  •  心在旅途
    2020-11-22 02:54

    Here's a much newer Kotlin solution for this which is much simpler than many of the answers written here, it uses anonymous class.

    val items = mutableListOf()
    
    inner class ItemHolder(view: View): RecyclerView.ViewHolder(view) {
        var textField: TextView = view.findViewById(android.R.id.text1) as TextView
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        rvitems.layoutManager = LinearLayoutManager(context)
        rvitems.adapter = object : RecyclerView.Adapter() {
    
            override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
                return ItemHolder(LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, parent, false))
            }
    
            override fun getItemCount(): Int {
                return items.size
            }
    
            override fun onBindViewHolder(holder: ItemHolder, position: Int) {
                holder.textField.text = items[position]
                holder.textField.setOnClickListener {
                    Toast.makeText(context, "Clicked $position", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
    

    I took the liberty to use android.R.layout.simple_list_item_1 as it's simpler. I wanted to simplify it even further and put ItemHolder as an inner class but couldn't quite figure out how to reference it in a type in the outer class parameter.

提交回复
热议问题