谁能告诉我如何使用Kotlin片段显示recyclerview吗?

问题描述 投票:0回答:1

enter code here实际上,我想使用recyclerview在一个片段中显示数据。我可以在活动中显示数据,但在片段中使用相同的代码,则不起作用。请您在这次隔离中的一点帮助将对我有很大帮助。我将不胜感激

这是适配器

class chatAdapter (val chatlist: ArrayList<ChatData>): RecyclerView.Adapter<chatAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    val v = LayoutInflater.from(parent?.context).inflate(R.layout.chat_row, parent, false)
    return ViewHolder(v)

}

override fun getItemCount(): Int {
    return chatlist.size

}

override fun onBindViewHolder(holder: ViewHolder, position: Int) {

    val chat: ChatData = chatlist[position]

    holder?.textViewName?.text = chat.doctorName
    holder?.textViewMessage?.text = chat.lastMessage
    holder?.textViewTime?.text = chat.timeStamp
}

class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView){
    val textViewName = itemView.findViewById<TextView>(R.id.docName)
    val textViewMessage = itemView.findViewById<TextView>(R.id.lastMsg)
    val textViewTime = itemView.findViewById<TextView>(R.id.timestamp)

}


}

数据类:

package com.example.myapplication

data class ChatData( val doctorName: String, val lastMessage: String , val timeStamp: String)

我需要帮助的片段代码

class ConsultFragment : Fragment() {



    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_consult, container, false)



    //This code is Unreachable in the fragment but it works perfectly fine in activity
    val recyclerView = view?.findViewById<RecyclerView>(R.id.docrecview)


    recyclerView?.layoutManager = LinearLayoutManager(this)



    val docs = ArrayList<DocData>()



    }


    override fun onCreate(savedInstanceState: Bundle?) {
        setHasOptionsMenu(true)
        super.onCreate(savedInstanceState)



    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        inflater.inflate(R.menu.menu, menu)
        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {

       val id = item.itemId
        if (id==R.id.consult)
        {
            activity?.let{
                val intent = Intent (it, doctors::class.java)
                it.startActivity(intent)
            }
        }

//        when (item.itemId) {
//            R.id.Consult -> {
//                activity?.let {
//                    val intent = Intent ([email protected], DocListFragment::class.java)
//                    startActivity(intent)
//                }
//            }
//        }
            return super.onOptionsItemSelected(item)
    }



}
kotlin android-recyclerview fragment
1个回答
0
投票

您正在谈论的代码将不会执行,因为它会在返回后放置。您可以从inlate函数中获取View,并在回收者视图的代码后返回它]

© www.soinside.com 2019 - 2024. All rights reserved.