【发布时间】:2020-03-27 14:52:22
【问题描述】:
我想在片段中使用 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 (this@ConsultFragment.context, DocListFragment::class.java)
// startActivity(intent)
// }
// }
// }
return super.onOptionsItemSelected(item)
}
}
【问题讨论】:
标签: kotlin android-recyclerview fragment