[英]Android ListView ArrayAdapter in fragment not work
I've been trying to understand why it doesn't work for a while, I've followed several guides and the procedure is always the same.我一直试图理解为什么它有一段时间不起作用,我遵循了几个指南,程序总是一样的。
The ArrayAdapter part returns a Context-related error: ArrayAdapter 部分返回与上下文相关的错误:
Screenshot with ArrayAdapter Error ArrayAdapter 错误的屏幕截图
I thought the problem may be related to the fragment but I was unable to solve it.我认为问题可能与片段有关,但我无法解决。 My goal is to try to add the array to the listview我的目标是尝试将数组添加到列表视图
menuFragment.xml 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菜单片段.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
}}
this
refers a Fragment
, you should use a Context
in ArrayAdapter constructor. this
指的是Fragment
,您应该在 ArrayAdapter 构造函数中使用Context
。
You can get the Context from getActivity()
or passing it to MenuFragment
您可以从getActivity()
获取 Context 或将其传递给MenuFragment
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.