我正在使用bottomnavigation视图开发android news应用程序,但是当我运行该应用程序时,却遇到了异常
Process: yodgorbek.komilov.musobaqayangiliklari, PID: 19590
java.lang.RuntimeException: Unable to start activity ComponentInfo{yodgorbek.komilov.musobaqayangiliklari/yodgorbek.komilov.musobaqayangiliklari.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.bottomnavigation.BottomNavigationView.setOnNavigationItemSelectedListener(com.google.android.material.bottomnavigation.BottomNavigationView$OnNavigationItemSelectedListener)' on a null object reference`
MainActivity.kt下面 MainActivity类:AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val bottomNavigationView = findViewById<BottomNavigationView>(R.id.bottom)
bottomNavigationView.setOnNavigationItemSelectedListener {
var selectedFragment = Fragment()
when (it.itemId) {
R.id.top_headline -> selectedFragment = TopHeadlinesFragment()
R.id.espn_news -> selectedFragment = ESPNFragment()
R.id.bbc_sport -> selectedFragment = BBCSportFragment()
R.id.football_italia -> selectedFragment = FootballItaliaFragment()
}
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.frame_layout, selectedFragment)
transaction.commit()
return@setOnNavigationItemSelectedListener true
}
}
}
activity_main.xml下面
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_gravity="bottom"
app:menu="@menu/bottomnews_nav"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</FrameLayout>
答案 0 :(得分:0)
在您的布局中,bottomNavigationView和framelayout都没有ID。两者都添加了ID