我知道我的layoutManager
和adapter
似乎为空,但我不太明白为什么它为空。
这是我的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)
}
这是我的模型类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)
}
尝试在由showcars()
插入onViewCreated
中调用方法oncreateView
,因为
The docs for Fragment.onCreateView()现在说:
建议仅在此方法中膨胀布局并移动在返回的View上操作onViewCreated(View,捆绑销售)。