如何将导航选项菜单设置为图标按钮而不是标题文本

How to set navigation option menu as icon button instead on title text

我可以将选项菜单设置为导航片段。

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"
<?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/my_menu_item"
        android:icon="@drawable/add_icon"
        android:title="@string/my_menu_item_title"
        app:showAsAction="always" />

</menu>

现在在您的片段中:

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)
    }
}

现在您的菜单出现了。请确保您的 activity 已正确设置 NavController,否则您的菜单将不会显示在工具栏中。你可以这样做。

val navController = this.findNavController(R.id.nav_host_fragment)
NavigationUI.setupActionBarWithNavController(this, navController)