[英]How to show menu item as action on a toolbar in a fragment
我已经设置了一个基本菜单和一个工具栏,如下所示:
home_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/notifications"
app:showAsAction="always"
android:title="@string/_ui_notifications"
android:icon="@drawable/ic_notifications_active"
/>
</menu>
fragment_home.xml
<-这是我想显示工具栏和菜单的地方
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context="._fragments.dash.HomeFragment"
xmlns:android="http://schemas.android.com/apk/res/android">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="64dp">
<Toolbar
android:id="@+id/homeToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="@drawable/app_logo_new"
android:scaleType="fitCenter"
android:padding="16dp"/>
</Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<ScrollView
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<androidx.viewpager.widget.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="240dp"/>
</LinearLayout>
</ScrollView>
</LinearLayout>
HomeFragment.kt
<- 这是我设置工具栏的片段
class HomeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_home, container, false)
appToolbar = view.findViewById(R.id.homeToolbar)
appToolbar.title = ""
appToolbar.inflateMenu(R.menu.home_menu)
appToolbar.setOnMenuItemClickListener{
when(it.itemId){
R.id.notifications -> {
Toast.makeText(activity!!, "Notifications", Toast.LENGTH_SHORT).show()
true
}
else -> {
Log.d("Menu", "Terrible things have happened in menu")
false
}
}
}
return view
}
}
通过这个简单的设置,我能够让工具栏工作。 同样单击菜单项“通知”会按预期发出祝酒词。
但是,菜单显示为下拉菜单,如下所示:
我如何把它变成一个动作?
编辑:
我使用属性.NoActionBar
禁用了主题中的默认操作栏
您在布局中使用了原生Toolbar
; 即, <Toolbar>
。 这忽略了菜单 XML 中的app:showAsAction
属性,因为它位于应用程序的命名空间中。
我猜您实际上打算使用库Toolbar
,在这种情况下,您希望将该布局元素更改为<androidx.appcompat.widget.Toolbar>
,并修改HomeFragment
类中的相关import
语句。
如果您出于某种原因确实打算使用本机Toolbar
,那么您需要使用android
命名空间中的showAsAction
属性; 即, android:showAsAction
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.