在片段中创建自定义列表视图时出错。必需 activity,已找到片段

Error creating custom listview in fragment. Required activity, found fragment

我决定在我的片段中创建自定义列表视图,但出现错误:

FragmentOne.kt: (41, 53): Type mismatch: inferred type is FragmentOne but Activity was expected.

代码如下。

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
    }
}

改变这个:

val myListAdapter = MyListAdapterInFragment(this,name,date,imgId)

为此:

val myListAdapter = MyListAdapterInFragment(activity,name,date,imgId)

使用view.context代替this

val myListAdapter = MyListAdapterInFragment(view.context,name,date,imgId)

Fragment Class 没有在其 hierarchy.As 结果中扩展 Context class我们不能用它代替 context.

但是,您可以通过两种方式将 context 放入片段中。

  1. 使用父级 ActivityFragment 在其上膨胀:输入 activity 在需要 context 的地方。 -> 在你的情况下: val myListAdapter = MyListAdapterInFragment(activity,name,date,imgId)

  2. 使用我们在 onCreateView() 方法中收到的 inflater 变量中的 context :输入 inflater.context -> 在你的情况下: 做一个属性val mContext:Context。 在 onCreateView() 方法中为其分配值 mContext = inflater.context。 然后在您的适配器对象中使用它作为 val myListAdapter = MyListAdapterInFragment(mContext,name,date,imgId)