[英]This error occur to me E/RecyclerView: No adapter attached; skipping layout
我知道我的layoutManager
管理器和adapter
似乎是 null,但我不太明白為什么是 null。
這是我的GpsFragment.kt
的代碼
class GpsFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
(context as AppCompatActivity).supportActionBar!!.title = "Gps"
val root = inflater.inflate(R.layout.fragment_gps, container, false)
showCars()
return root
}
private fun showCars(){
val cars = listOf(
Cars("Bezza","0.17263","3.267834"),
Cars("Bezza","0.17263","3.267834"),
Cars("Bezza","0.17263","3.267834"),
Cars("Bezza","0.17263","3.267834")
)
myCarlist?.layoutManager = LinearLayoutManager(activity)
myCarlist?.adapter = CarAdapter(cars)
}
這是我的 model class Cars.kt
的代碼
data class Cars(val name: String = "-",
val latitude: String = "-",
val longtitude: String = "-")
這是我的適配器CarAdapter.kt
的代碼
class CarAdapter (private val cars : List<Cars>) : RecyclerView.Adapter<CarAdapter.CarViewHolder>(){
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CarViewHolder {
val inflater = LayoutInflater.from(parent.context).inflate(R.layout.list_layout, parent, false)
return CarViewHolder(inflater)
}
override fun getItemCount() = cars.size
override fun onBindViewHolder(holder: CarViewHolder, position: Int) {
val car = cars[position]
holder.view.carname.text = car.name
holder.view.latitude.text = car.latitude
holder.view.longtitude.text = car.longtitude
}
class CarViewHolder(val view:View) : RecyclerView.ViewHolder(view)
}
嘗試在onViewCreated
oncreateView
中調用你的方法showcars()
因為
Fragment.onCreateView() 的文檔現在說:
建議只在該方法中擴充布局,將對返回View進行操作的邏輯移至onViewCreated(View, Bundle)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.