Android 如何将导航选项菜单设置为标题文本上的图标按钮
我可以将选项菜单设置为导航片段Android 如何将导航选项菜单设置为标题文本上的图标按钮,android,navigation,Android,Navigation,我可以将选项菜单设置为导航片段 class NavigationtFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { ... setHasOptionsMenu(true) }
class NavigationtFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
...
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
// set the option menu
}
}
是否可以将其替换为“添加图标”按钮
试试这个
Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.ic_add);
toolbar.setOverflowIcon(drawable);
首先创建menu.xml文件并添加上面显示的图标
android:icon="@drawable/add_icon"
现在你的菜单出现了。确保使用NavController正确设置了“活动”,否则您的菜单将不会显示在工具栏中。你可以这样做
val navController = this.findNavController(R.id.nav_host_fragment)
NavigationUI.setupActionBarWithNavController(this, navController)
您正在尝试以片段形式显示菜单吗?你能提供更多详细信息吗?基本上它需要添加菜单xml文件,然后将其配置到片段中,检查udacity官方指南的导航章节以查找更多详细信息。添加了我的答案,尝试一下,并让我知道它是如何运行的。是否只是将菜单图标替换为添加图标?可以让它作为按钮而不是菜单按钮使用吗?
app:showAsAction=“always”
是我问题的重点,非常感谢。
class NavigationtFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
...
setHasOptionsMenu(true)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
// set the option menu
inflater.inflate(R.menu.your_menu, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.my_menu_item -> {
// Add your action
}
}
return super.onOptionsItemSelected(item)
}
}
val navController = this.findNavController(R.id.nav_host_fragment)
NavigationUI.setupActionBarWithNavController(this, navController)