【发布时间】:2021-02-18 14:07:37
【问题描述】:
我想向我的 MainActivity 工具栏添加自定义视图。 因此,我创建了包含视图的 layout.xml 文件,并将其添加到 main_menu.xml,但我永远无法从 Activity 的 onPrepareOptionsMenu 中获取它。
main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/contact_search"
android:icon="@drawable/ic_search"
android:title="Search"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="androidx.appcompat.widget.SearchView" />
<item
android:id="@+id/currentServerViewItem"
android:title="My account"
app:actionLayout="@layout/main_toolbar_views"
app:showAsAction="always"/>
<item
android:id="@+id/action_aboutus"
android:orderInCategory="100"
android:title="About us"
app:showAsAction="never" />
</menu>
main_toolbar_views.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"
android:layout_width="32dp"
android:layout_height="32dp">
<TextView
android:id="@+id/currentServerTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/circle_white"
android:gravity="center"
android:padding="4dp"
android:text="UU"
android:textColor="@color/colorWhite"
android:textSize="14sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
private var currentServerTextView: TextView? = null
....
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu, menu)
searchView = menu?.findItem(R.id.contact_search)?.actionView as SearchView
searchView?.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
return true
}
override fun onQueryTextChange(newText: String?): Boolean {
newText?.let {
mainViewModel.setSearchable(it)
}
return true
}
})
return super.onCreateOptionsMenu(menu)
}
.....
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
// Here i get a nullPointer exception
val menuItem = menu?.findItem(R.id.currentServerViewItem)?.actionView as ConstraintLayout
currentServerTextView = menuItem.findViewById(R.id.currentServerTextView) as TextView
currentServerTextView?.setOnClickListener {
toast("Text Clicked!!!")
}
return super.onPrepareOptionsMenu(menu)
}
尝试调试 menuItem 时,我得到一个 nullPointerException,尽管菜单不为空。 同样在工具栏而不是 TextView 布局(这是一个圆形 textView)中,我只看到 MyAccount 标题。
为什么会这样?
【问题讨论】:
标签: android nullpointerexception toolbar menuitem android-appbarlayout