我已经创建了一个Android应用程序,使用 NavigationDrawer
. 当应用程序创建时,默认设置了一个图标菜单,放在工具栏的左边。而我的目的是增加另一个图标,例如,放置在工具栏的右侧。我已经尝试了很多教程,按照他们的步骤一步一步地去做,但我无法实现。谁能帮帮我?
你需要创建一个菜单来实现这个任务。例如,你需要创建一个菜单来实现这个任务。
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.comguidetopicsresourcesmenu-resource。
如果您使用的是设置为Actionbar(setSupportActionBar(Toolbar))的工具栏或单独的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
因为它在弹出菜单中。
如果您只使用工具条(没有设置为行动条)。
<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" />
在活动中
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>
在你的menu.xml中添加.xml,然后在OnCreateView中:setHasOptionsMenu(true);关闭OncreateView下面写上这个方法:。
<item
android:title="icon"
app:showAsAction="always"
android:id="@+id/menuitem_icon"
android:icon="@drawable/micon"
>
</item>
然后在OnCreateView中:setHasOptionsMenu(true); 关闭OncreateView下面写这个方法。
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.icon, menu);
...
}