我有一个片段里面有RecyclerAdapter。我想在onCreateView
方法中初始化适配器,但它在此语句中抛出"Type mismatch. Required : Context , Found : FragmentActivity"
错误
我不知道为什么第一个显示这个错误,第二个不包含编译时错误。
显示错误
recyclerView!!.adapter = RestaurantMenuAdapter(activity)
未显示错误
recyclerView!!.layoutManager = LinearLayoutManager(activity)
Fragment.kt
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_restaurant_menu, container, false)
recyclerView = view.findViewById(R.id.restaurant_container)
recyclerView!!.adapter = RestaurantMenuAdapter(activity)
recyclerView!!.layoutManager = LinearLayoutManager(activity)
RecyclerAdapter.kt
class RestaurantMenuAdapter (val context : Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val inflater = parent.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
return object : RecyclerView.ViewHolder(inflater.inflate(R.layout.item_menu1, parent, false)) {
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
}
override fun getItemCount(): Int {
return 10
}
}
4条答案
按热度按时间ogsagwnx1#
将此更改为:
收件人:
lrpiutwd2#
到
ftf50wuq3#
保持适配器原样,只需使用“活动!!”,在此初始化适配器。
您的适配器将保持不变。
1l5u6lss4#
将回收器适配器从上下文更改为活动。