我目前正在学习 Kotlin,在学习 BottomNaivgationView
教程时,我遇到了应用程序在启动后立即关闭的错误。经过多次测试,我发现这是由我实现的 findViewbyId()
从菜单中选择视图造成的。但是,我不知道如何修复它。
MainActivity.kt
val TAG = "MainActivity"
val bottom_navigation : BottomNavigationView = findViewById(R.id.bottom_navigation)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val homeFragment = HomeFragment()
val listsFragment = ListsFragment()
val searchFragment = SearchFragment()
bottom_navigation.setOnNavigationItemSelectedListener {
when (it.itemId) {
R.id.nav_home -> {
setCurrentFragment(homeFragment)
Log.i(TAG, "Home Selected")
}
R.id.nav_lists -> {
setCurrentFragment(listsFragment)
Log.i(TAG, "My Lists Selected")
}
R.id.nav_search -> {
setCurrentFragment(searchFragment)
Log.i(TAG, "Search Selected")
}
}
true
}
}
private fun setCurrentFragment(fragment : Fragment) =
supportFragmentManager.beginTransaction().apply {
replace(R.id.fl_wrapper, fragment)
commit()
}
activity_main.xml
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/fl_wrapper"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/bottom_navigation" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="@+id/bottom_navigation"
android:layout_alignParentBottom="true"
android:background="?android:attr/windowBackground"
app:itemBackground="@color/colorPrimary"
app:itemIconTint="@drawable/nav_item_colour_selected"
app:labelVisibilityMode="unlabeled"
app:menu="@menu/bottom_nav_menu"/>
</RelativeLayout>
答案 0 :(得分:1)
您不能在 findViewById()
活动生命周期方法中使用 setContentView(R.layout.activity_main)
设置活动布局之前调用 onCreate()
..
在 onCreate()
和 setContentView(R.layout.activity_main)
之前,活动类/行为尚未附加到其视图/布局。所以没有布局为了在..中找到一个视图。
所以你需要转移
val bottom_navigation : BottomNavigationView = findViewById(R.id.bottom_navigation)
成为:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val bottom_navigation : BottomNavigationView = findViewById(R.id.bottom_navigation)
val homeFragment = HomeFragment()
//......
答案 1 :(得分:1)
您可以使用惰性属性。
val bottom_navigation: BottomNavigationView by lazy { findViewById(R.id.bottom_navigation) }