我在一个片段中创建了一个列表视图 列表视图的适配器存在空指针异常 但是Arraylist和适配器都不为空。
错误:lvElevator不能为空
错误是针对以下行
lvElevator.adapter = EAdapter
var EList=ArrayList<E1List>()
class EDetails: Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
EList.add(E1List(1))
EList.add(E1List(2))
var EAdapter = EleAdapter(EList)
lvElevator.adapter = EAdapter
return inflater.inflate(R.layout.fragment_elevators, container, false)
}
inner class EleAdapter : BaseAdapter {
var EListAdapter = ArrayList<E1List>()
constructor(EListAdapter: ArrayList<E1List>) : super() {
this.EListAdapter = EListAdapter
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
var myView = layoutInflater.inflate(R.layout.elevator_ticket, null)
var myEle = EListAdapter[position]
myView.tvEnum.text = myEle.elevatornum.toString()
return myView
}
override fun getItem(position: Int): Any {
return EListAdapter[position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getCount(): Int {
return EListAdapter.size
}
}
}
答案 0 :(得分:0)
您正在尝试在片段为xml布局文件充气之前定义lvElevator。 有两种解决方法。
1)代替使用 onViewCreated()
方法将数据加载到视图中。并使用onCreateView方法仅使视图膨胀。
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
EList.add(E1List(1))
EList.add(E1List(2))
var EAdapter = EleAdapter(EList)
lvElevator.adapter = EAdapter
}
2)修改onCreateView()
方法,如下所示。
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Define views manually..
val view = inflater.inflate(R.layout.fragment_elevators, container, false)
val lvElevator = view.findViewById<ListView>(R.id.lvElevator)
EList.add(E1List(1))
EList.add(E1List(2))
var EAdapter = EleAdapter(EList)
lvElevator.adapter = EAdapter
return view
}
作为有经验的开发人员,我建议使用第一种方法,因为该方法仅在布局膨胀完成后才会出现。