ListView ID调用为null? (科特琳)

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

[我不是Kotlin的新手,我试图建立一个HomePage,其中有一个BottomNavigation具有3个Fragment页面,但是在其中1个页面中我设置了一个ListView,每当我调用ID时,它都会给出以下错误(Caused by: java.lang.IllegalStateException: categoryListView must not be null

这是我在主页上显示内容的方式:

class HomePage : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {

    lateinit var adapter : CategoryAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home_page)

        adapter = CategoryAdapter(this, DataService.categories)
        categoryListView.adapter = adapter

        navView.setNavigationItemSelectedListener(this)

        bottomNavigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)

        replaceFragment(HomeFragment())
    }

    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
        when(item.itemId) {
            R.id.Bottom_Nav_Home -> {
                println("Home pressed")
                replaceFragment(HomeFragment())
                return@OnNavigationItemSelectedListener true
            }
            R.id.Bottom_Nav_Notifs -> {
                println("Notification pressed")
                replaceFragment(NotifsFragment())
                return@OnNavigationItemSelectedListener true
            }
            R.id.Bottom_Nav_List -> {
                println("List pressed")
                replaceFragment(ListFragment())
                return@OnNavigationItemSelectedListener true
            }
        }
        false
    }

    private fun replaceFragment(fragment: Fragment) {
        val fragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.NavPageFragment, fragment)
        fragmentTransaction.commit()
    }
}

我正确吗?还是应该在其他地方调用categoryListView?因为我尝试了我的ListFragment,这是我的活动代码所在的位置,并且出现了上下文错误

这是Fragment活动的外观:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/Bottom_List"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Fragments.ListFragment">

    <ListView
        android:id="@+id/categoryListView"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
android-fragments kotlin android-listview
1个回答
0
投票

您正在尝试使活动中的categoryListView解析,但据我所知,它是该片段的一部分。这根本行不通。

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