我使用NavigationDrawer创建了一个Android应用程序。创建应用程序时,默认情况下会设置一个图标菜单,放在toolBar的左侧。我的目标是添加另一个图标,例如,在工具栏的右边。我试过很多教程,一步一步地去做,但我做不到。有人能帮我吗?

发布于 2020-05-26 14:53:28
您需要创建一个菜单来完成此任务。例如;
res/menu/menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/new_item"
android:icon="@drawable/new_icon"
app:showAsAction="ifRoom">
</item>
</menu>如果您已经有了菜单,那么您可以继续使用它。
创建菜单后,需要对其进行充气。
public class MainActivity extends AppCompatActivity {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}有关使用菜单资源:https://developer.android.com/guide/topics/resources/menu-resource的详细信息,请参阅以下内容
发布于 2020-05-26 14:52:17
在活动中
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater: MenuInflater = menuInflater
inflater.inflate(R.menu.game_menu, menu)
return true}
处理对菜单项的单击
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle item selection
return when (item.itemId) {
R.id.new_game -> {
newGame()
true
}
R.id.help -> {
showHelp()
true
}
else -> super.onOptionsItemSelected(item)
}}
菜单文件夹game_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/new_game"
android:icon="@drawable/ic_new_game"
android:title="@string/new_game"
android:showAsAction="always"/> // this icon will be always shown
<item android:id="@+id/help"
android:icon="@drawable/ic_help"// add you icon image
android:title="@string/help"
android:showAsAction="ifRoom"/> // this icon will be shown if there is space available
</menu>发布于 2020-05-26 14:52:32
如果您将工具栏设置为Actionbar (setSupportActionBar(工具栏))或仅使用Actionbar:
在你的活动中:
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
getMenuInflater().inflate(R.layout.menu_home, menu)
return true
}在res -> menu文件夹中添加一个名为menu_home的新文件(如果菜单文件夹不存在,请创建一个文件):
将需要的项目添加到menu_home文件中:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/item_01"
android:title="@string/my_title"
android:icon="@drawable/my_icon"
app:showAsAction="ifRoom"/>
...
</menu>showAsAction="ifRoom"使图标在工具栏中可用,如果有空间的话。当never进入弹出式菜单时,您还可以选择它。
如果您只使用工具栏(不设置为Actionbar)::
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
app:menu="@menu/menu_home"
android:layout_height="?android:attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />https://stackoverflow.com/questions/62024677
复制相似问题