在片段中创建自定义列表视图时出错所需活动,找到片段

问题描述 投票:1回答:3

我决定在我的片段中创建自定义列表视图,但是我收到一个错误:

FragmentOne.kt:(41,53):类型不匹配:推断类型是FragmentOne但预期是Activity。

代码如下。

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
    }
}
android android-fragments kotlin android-listview
3个回答
0
投票

Fragment类不会在其层次结构中扩展Context类。因此,我们无法将其传递给上下文。

但是,您可以通过两种方式在片段中引入上下文。

  1. 使用片段膨胀的父Activity:通过在需要activity的位置键入context。 - >在你的情况下:val myListAdapter = MyListAdapterInFragment(activity,name,date,imgId)
  2. 使用我们在inflater方法中收到的onCreateView()变量的上下文:通过输入inflater.context - >在您的情况下:创建属性val mContext:Context。在onCreateView()方法中为其赋值mContext = inflater.context。然后在你的适配器对象中使用它作为val myListAdapter = MyListAdapterInFragment(mContext,name,date,imgId)

0
投票

改变这个:

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

对此:

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


0
投票

使用view.context而不是this

val myListAdapter = MyListAdapterInFragment(view.context,name,date,imgId)
© www.soinside.com 2019 - 2024. All rights reserved.