我被困了一段时间,试图使BottomNavigationView
对选择做出正确的反应,但是使它起作用后,我仍然不明白为什么以前的代码不起作用。这就是我所拥有的:
activity_main.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="64sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_nav_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:menu="@menu/bottom_nav_menu"/>
</androidx.constraintlayout.widget.ConstraintLayout>
bottom_nav_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/bottom_nav_unseen"
android:icon="@drawable/ic_unseen"
android:title="Unseen" />
<item
android:id="@+id/bottom_nav_all"
android:icon="@drawable/ic_list_black_24dp"
android:title="All" />
<item
android:id="@+id/bottom_nav_favorites"
android:icon="@drawable/ic_star_border_black_24dp"
android:title="Favorites" />
</menu>
MainActivity.kt
package com.example.bottomnavdebug
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bottom_nav_view.setOnNavigationItemSelectedListener {
when (bottom_nav_view.selectedItemId) {
R.id.bottom_nav_unseen -> text_view.text = "Unseen"
R.id.bottom_nav_all -> text_view.text = "All"
R.id.bottom_nav_favorites -> text_view.text = "Favorites"
}
true
}
}
}
此代码将要求我选择两次要适当更改文本的项目,并且即使我选择了“全部”或“收藏夹”。 因此,我然后更改了以下代码块:
bottom_nav_view.setOnNavigationItemSelectedListener {
when (bottom_nav_view.selectedItemId) {
R.id.bottom_nav_unseen -> text_view.text = "Unseen"
R.id.bottom_nav_all -> text_view.text = "All"
R.id.bottom_nav_favorites -> text_view.text = "Favorites"
}
true
}
到
bottom_nav_view.setOnNavigationItemSelectedListener {
when (it.itemId) {
R.id.bottom_nav_unseen -> text_view.text = "Unseen"
R.id.bottom_nav_all -> text_view.text = "All"
R.id.bottom_nav_favorites -> text_view.text = "Favorites"
}
true
}
,现在它的行为确实正确。选择项目后,它始终会显示正确的文本。为什么第一段错误?看起来他们做的完全一样。