我有一个包含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
}
}
答案 0 :(得分:7)
将此更改为 - :
recyclerView!!.adapter = RestaurantMenuAdapter(activity)
要 - :
recyclerView!!.adapter = RestaurantMenuAdapter(activity.applicationContext)
答案 1 :(得分:4)
recyclerView!!.adapter = RestaurantMenuAdapter(this)
收件人
recyclerView!!.adapter = RestaurantMenuAdapter(this.requireActivity())
答案 2 :(得分:0)
更换Recycler适配器 从上下文到活动。
class RestaurantMenuAdapter (val context : Activity) : 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
}
}
答案 3 :(得分:0)
保持适配器不变,只需使用“活动!!”在哪里初始化适配器。
protected static $serialize = true;
您的适配器将保持不变。
recyclerView.adapter = RestaurantMenuAdapter(activity!!)