I have a Action Bar where i want to add one help button using Menu. I am using Android 3.0. My Menu code is like below:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/h开发者_运维技巧elp_btn"
android:icon="@drawable/help"
android:title="Help"
android:showAsAction="ifRoom|withText"
/>
Now how can i add this menu in the action bar??
The same way you create regular menus:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
http://developer.android.com/guide/topics/ui/menus.html#OptionsMenu
Update;
You can inflate a menu like this @override
Put in res/menu/YOUR_MENU.xml
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.YOUR_MENU, menu);
return true;
}
I know this is a pretty old question, but I'll throw an answer at it anyway. If you're dealing with a Fragment, you'll need to let the system know you'd like to contribute to the action bar or onCreateOptionsMenu
will never be called. https://stackoverflow.com/a/10049807/725752
Now with Jetpack Compose , you don't need separate menu XML
Scaffold(
modifier = Modifier.fillMaxSize(),
topBar= {
TopAppBar(
title = {
Text(text = "Create New Recipe")
},
navigationIcon = {
IconButton(onClick = { }) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = "Back"
)
}
},
backgroundColor = Color.Blue,
contentColor = Color.White,
elevation = 2.dp,
actions = {
IconButton(onClick = {
uiController.hideSoftKeyboard()
...
}) {
Icon(
contentDescription = "Help",
painter = painterResource(R.drawable.help)
)
}
}
)
}, content = {
}
})
Here topBar
contains code for Action Bar and actions
contains menu button
Reference- https://androidlearnersite.wordpress.com/2021/08/03/jetpack-compose-1-0-0-sample-codes/
精彩评论