Android添加菜单栏

发布时间 2023-09-04 22:14:35作者: 夜空中最亮de星

import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();

if(id == R.id.item11)
{
Toast.makeText(this, "点击了第一个菜单", Toast.LENGTH_SHORT).show();
}

return true;

}

AndroidMainfest.xml
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Base.Theme.MyApplication" parent="Theme.Material3.DayNight">
<!-- Customize your light theme here. -->
<!-- <item name="colorPrimary">@color/my_light_primary</item> -->
</style>

<style name="Theme.MyApplication" parent="Base.Theme.MyApplication" />
</resources>


res目录 -> 创建Android resource 目录 -> menu, main_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/item11" android:title="显示启动item" />

</menu>