The easiest solution is to go ahead and create a menu, but make its sole menu item appear always instead of in the overflow menu.
First create a menu xml file with your button as a menu item, and mark it to be shown always so it won't be put in an overflow menu.
<?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/action_settings"
android:title="@string/settings"
android:icon="@drawable/ic_settings_24dp"
app:showAsAction="always" />
</menu>
If you switch to putting an App Bar directly in your layout ( see here , and here ), and your button is global to your whole activity (not just for a specific fragment) you can set this menu on your MaterialToolbar in your layout xml using app:menu
. Otherwise, you need to set the menu by overriding onCreateOptionsMenu()
in your Activity or Fragment:
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.top_bar_menu, menu)
return true
}
To respond to button presses from the menu, you override onOptionsItemSelected()
:
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.action_settings -> {
// do something
true
}
else -> super.onOptionsItemSelected(item)
}
}
If you want to do this from a Fragment, call setHasOptionsMenu(true)
in your fragment's onViewCreated()
, and you can override the same two above functions in your Fragment.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.