Android ListView ArrayAdapter在片段中不起作用

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

我一直试图理解为什么一段时间不起作用,我遵循了一些指南,并且过程始终相同。

ArrayAdapter部分返回与上下文相关的错误:

Screenshot with ArrayAdapter Error

我以为问题可能与碎片有关,但我无法解决。我的目标是尝试将数组添加到listview

menuFragment.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MenuFragment">


    <ListView
        android:id="@+id/list_menu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
    />
</LinearLayout>

MenuFragment.kt

class MenuFragment : Fragment() {


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?

    ): View? {

        val view: View = inflater.inflate(R.layout.fragment_menu, container, false)

        val arrayAdapter: ArrayAdapter<*>
        val menuItems = arrayOf("wine", "beer", "pizza", "steak", "chicken")

        var mListView = list_menu

        arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, menuItems)

        mListView.adapter = arrayAdapter


        return view

    }}
android kotlin android-listview android-arrayadapter
1个回答
0
投票

[this指代Fragment,应在ArrayAdapter构造函数中使用Context

您可以从getActivity()中获取上下文或将其传递给MenuFragment

© www.soinside.com 2019 - 2024. All rights reserved.