当前位置: 首页 > 知识库问答 >
问题:

类型不匹配:推断类型为GroupsFragment,但为Context!预料之中

祁博涛
2023-03-14

我正在学习如何解析一个JSON,并使用数据将其放入回收视图列表中,我正在片段中完成。这让很多人头疼,也有各种各样的错误。第一个是上下文!这是GroupFragment.kt文件内容:

package com.locos.riders

import android.graphics.Color
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.fragment_groups.*
import com.locos.riders.UserListAdapter

class GroupsFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_groups, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        userlist.layoutManager = LinearLayoutManager(this)
        userlist.adapter = UserListAdapter


    }


}

当我运行这个时,我得到了类型不匹配:推断的类型是GroupsFragment,但上下文!这是意料之中的。

在我的UserListAdapter.kt我试图加载userlist_row,我也找不到这个布局资源,即使文件是在布局/文件夹中创建的:

package com.locos.riders

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.userlist_row.view.*

class UserListAdapter: RecyclerView.Adapter<CustomViewHolder>() {

    // number of items
    override fun getItemCount(): Int {
        return 3
    }

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): CustomViewHolder {
        val layoutInflater = LayoutInflater.from(parent?.context)
        val cellForRow = layoutInflater.inflate(R.layout.userlist_row, parent, false)
        return CustomViewHolder(cellForRow)
    }

    override fun onBindViewHolder(holder: CustomViewHolder, position: Int) {
        holder.view.listTitle?.text = "123"
    }

}

class CustomViewHolder(val view: View): RecyclerView.ViewHolder(view) {

}

共有1个答案

何琨
2023-03-14

你有一些错别字,通常可以通过阅读错误来修复。

以下是这些错误的解决方案:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    userlist.layoutManager = LinearLayoutManager(context) // <- context == getContext() in java
    userlist.adapter = UserListAdapter() // <- put parentheses over here
}
 类似资料: