Android 为什么我不能在片段中使用Listview

Android 为什么我不能在片段中使用Listview,android,listview,kotlin,fragment,Android,Listview,Kotlin,Fragment,如何在Fragment中使用Listview。我在一个活动中实现了几乎类似的代码,在那里它工作得非常好。但是对于片段,我只做了一点修改,以避免Android Studio显示的错误。但是,它在这里不起作用。 这是我的密码: class FragmentMascot : Fragment() { override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bund

如何在
Fragment
中使用
Listview
。我在一个
活动
中实现了几乎类似的代码,在那里它工作得非常好。但是对于
片段
,我只做了一点修改,以避免
Android Studio
显示的错误。但是,它在这里不起作用。 这是我的密码:

class FragmentMascot : Fragment() {
  override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val view= inflater!!.inflate(R.layout.fragment_mascot, container, false)
    val listview = view.findViewById<ListView>(R.id.maskot_list)
    //listview.adapter = MaskotAdapter(this) -> this does't work in fragment but worked in activity
    listview.adapter = MaskotAdapter(context)
    return view
  }

您应该在实例化适配器时使用活动上下文
(getActivity)
。片段没有上下文。

列表没有出现吗?还是有致命的例外

以及

使用RecyclerView。
每次调用inflate而不使用getView()中的holder模式是一种低效的方法。

我终于找到了答案。我们还需要将活动作为一个参数。因此,在问题中提到的准则中:

listview.adapter = MaskotAdapter(context)
将更改为listview.adapter=MaskotAdapter(上下文,活动) 及

行应改为

private class MaskotAdapter(context: Context, activity: Activity): BaseAdapter() {
listview.adapter = MaskotAdapter(context,activity) 
private class MaskotAdapter(context: Context, activity: Activity): BaseAdapter() {

在这里,活动参数非常重要。您可以像这样更改:

listview.adapter = MaskotAdapter(context)
将变为

private class MaskotAdapter(context: Context, activity: Activity): BaseAdapter() {
listview.adapter = MaskotAdapter(context,activity) 
private class MaskotAdapter(context: Context, activity: Activity): BaseAdapter() {

行应改为

private class MaskotAdapter(context: Context, activity: Activity): BaseAdapter() {
listview.adapter = MaskotAdapter(context,activity) 
private class MaskotAdapter(context: Context, activity: Activity): BaseAdapter() {

希望它能起作用。但是,如果可能的话,请转到recyclerView,因为这样内存效率更高。

U应该使用recycler视图而不是ListView,后者更灵活,内存管理更方便。不工作??它显示了一些错误吗?这看起来很相似,但这是针对Java的,这是针对Kotlinplease attach log的。