特定于带有自定义 xml 视图的菜单项的视图绑定,而不是 数据绑定:
partial_menu_sample_view.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="?actionBarSize"
android:layout_height="?actionBarSize"
android:clipToPadding="false"
android:focusable="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:contentDescription="@null"
android:src="@drawable/ic_sample"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textview_sample"
android:visibility="gone"
app:layout_constraintBottom_toTopOf="@id/guideline_horizontal_center"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@id/guideline_vertical_center"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_sample.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar_sample"/>
</LinearLayout>
SampleActivity.kt
class SampleActivity() {
lateinit var binding: ActivitySampleBinding
var menuSampleViewBinding: PartialMenuSampleViewBinding? = null
...
override fun onCreate() {
super.onCreate()
binding = ActivitySampleBinding.inflate(layoutInflater)
setContentView(binding.root)
// make sure to set the toolbar
setSupportActionBar(binding.toolbarSample)
}
...
override fun onCreateOptionsMenu() {
// inflate the menu to show on your toolbar
// replace with your own menu xml
binding.toolbarProduct.inflateMenu(R.menu.activity_sample)
with(binding.toolbarProduct.menu) {
findItem(R.id.menu_item_cart)?.actionView?.let {
menuSampleViewBinding = PartialMenuSampleViewBinding.bind(it)
}
// handle other menu items here
}
}
...
fun customFunction() {
// use as needed
menuSampleViewBinding?.textviewSample?.text = "1"
menuSampleViewBinding?.root?.setOnClickListeners { /* add what you need */ }
}
}
在菜单项上有徽章计数的用例中使用它。工作正常。