【发布时间】:2019-08-15 08:45:40
【问题描述】:
我决定在我的片段中创建 自定义列表视图,但我收到一个错误:
FragmentOne.kt: (41, 53): 类型不匹配:推断类型为 FragmentOne 但预计会有活动。
代码如下。
FragmentOne.kt
class FragmentOne : Fragment() {
val name = arrayOf(
"First catch","Second catch","Third catch","Fourth catch"
)
val date = arrayOf(
"01.01.2019", "02.02.2010", "03.03.2003", "04.04.2004"
)
val imgId = arrayOf(
R.drawable.fish
)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.screen1, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val myListAdapter = MyListAdapterInFragment(this,name,date,imgId)
ListViewInFragment.adapter = myListAdapter
}
}
MyListAdapterInFragment.kt
class MyListAdapterInFragment(private val context: Activity, private val title: Array<String>, private val date: Array<String>, private val imgid: Array<Int>)
: ArrayAdapter<String>(context, R.layout.list_iteminfragment, title) {
override fun getView(position: Int, view: View?, parent: ViewGroup): View {
val inflater = context.layoutInflater
val rowView = inflater.inflate(R.layout.list_iteminfragment, null, true)
val titleText = rowView.findViewById(R.id.title) as TextView
val imageView = rowView.findViewById(R.id.imageViewInFragment) as ImageView
val subtitleText = rowView.findViewById(R.id.date) as TextView
titleText.text = title[position]
imageView.setImageResource(imgid[position])
subtitleText.text = date[position]
return rowView
}
}
【问题讨论】:
-
MyListAdapterInFragment(this,name,date,imgId)– 将this更改为activity。 -
不知道为什么,但是您的代码应该在此处显示错误
MyListAdapterInFragment(this,name,date,imgId),因为您正在传递需要活动上下文的片段上下文
标签: android android-fragments kotlin android-listview