我决定在片段中创建自定义列表视图,但出现错误:
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
}
}
答案 0 :(得分:0)
更改此:
val myListAdapter = MyListAdapterInFragment(this,name,date,imgId)
对此:
val myListAdapter = MyListAdapterInFragment(activity,name,date,imgId)
答案 1 :(得分:0)
使用view.context
代替this
val myListAdapter = MyListAdapterInFragment(view.context,name,date,imgId)
答案 2 :(得分:0)
片段类不会在其层次结构中扩展 Context类,因此,我们无法通过它代替 context 。
不过,您可以通过两种方式将上下文带入片段。
使用父级 Activity (在其上扩展了 Fragment ):在需要activity
的地方键入context
。
->在您的情况下:
val myListAdapter = MyListAdapterInFragment(activity,name,date,imgId)
使用inflater
方法中收到的onCreateView()
变量中的 context :键入inflater.context
->在您的情况下:
设置一个属性val mContext:Context
。
在onCreateView()方法中为其分配值mContext = inflater.context
。
然后在适配器对象中将其用作
val myListAdapter = MyListAdapterInFragment(mContext,name,date,imgId)