ListView可以出现在Activity
中,但不能出现在Fragment
中。但是,我在Kotlin和Android Studio 3.0中使用了相同的代码吗?
这是我的片段代码:
class testFrag : Fragment() {
var adapter : mo3dAdapter?=null
var listOfMkabala = ArrayList<MeetingDetails>()
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.fragment_test, container, false)
listOfMkabala .add ( MeetingDetails(" nour1", "ahmed1" , "aya1"))
listOfMkabala .add ( MeetingDetails(" nour2", "ahmed2" , "aya2"))
listOfMkabala .add ( MeetingDetails(" nour3", "ahmed3" , "aya3"))
listOfMkabala .add ( MeetingDetails(" nour4", "ahmed4" , "aya4"))
listOfMkabala .add ( MeetingDetails(" nour5", "ahmed5" , "aya5"))
listOfMkabala .add ( MeetingDetails(" nour6", "ahmed6" , "aya6"))
adapter = mo3dAdapter (context ,listOfMkabala)
tv1.adapter = adapter
}
fun test ( view: View){
}
这是我的适配器:
inner class mo3dAdapter: BaseAdapter {
var listOfMkabaln= ArrayList<MeetingDetails>()
var context:Context?=null
constructor(context:Context, listOfMkabaln: ArrayList<MeetingDetails>):super(){
this.listOfMkabaln=listOfMkabaln
this.context=context
}
override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
val mo3d = listOfMkabaln[p0]
var inflator = context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
var myView = inflator.inflate(R.layout.fragment_test, null)
myView.text1.text = mo3d.name1!!
myView.text2.text = mo3d.name2!!
myView.text3.text = mo3d.name3!!
return myView
}
override fun getItem(p0: Int): Any {
return listOfMkabaln[p0]
}
override fun getItemId(p0: Int): Long {
return p0.toLong()
}
override fun getCount(): Int {
return listOfMkabaln.size
}
}
最佳答案
在初始化后,您应该制作一个return语句
onCreateView()
。
您正在使用kotlin-android-extensions
直接获取 View 。如果使用这种方式,则只有在创建 View 后才能获取LisView
。
您的代码应如下所示。
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.fragment_test, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
listOfMkabala .add ( MeetingDetails(" nour1", "ahmed1" , "aya1"))
listOfMkabala .add ( MeetingDetails(" nour2", "ahmed2" , "aya2"))
listOfMkabala .add ( MeetingDetails(" nour3", "ahmed3" , "aya3"))
listOfMkabala .add ( MeetingDetails(" nour4", "ahmed4" , "aya4"))
listOfMkabala .add ( MeetingDetails(" nour5", "ahmed5" , "aya5"))
listOfMkabala .add ( MeetingDetails(" nour6", "ahmed6" , "aya6"))
adapter = mo3dAdapter (context ,listOfMkabala)
tv1.adapter = adapter
}
onViewCreated()
在创建 View 后运行。这样可以确保您的 View 已经创建。您还为适配器传递了相同的布局。
在您的适配器代码中,将
R.layout.fragment_test
更改为模型布局。var myView = inflator.inflate(R.layout.fragment_test, null)
希望能帮助到你:)