生成一个menu的文件夹中,在文件中生成一个option.xml
MainActivity.java文件
package com.example.imoocapplication; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { //加载菜单资源 getMenuInflater().inflate(R.menu.option, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.save: Toast.makeText(this, "保存", Toast.LENGTH_SHORT).show(); break; case R.id.setting: Toast.makeText(this, "设置", Toast.LENGTH_SHORT).show(); break; case R.id.exit: finish(); break; } return super.onOptionsItemSelected(item); } }
xml界面用于生成界面
<?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"> <!--showAsAction属性值:always: 直接在标题栏显示 never: 不显示 withText: 控制图标和文本一起显示 ifRoom: 有空间就显示 422222222222222222222222222222222222222222222222222222222222222445454545454545454545454545454545454545454545454588 --> <item android:title="保存" android:id="@+id/save" android:icon = "@mipmap/ic_launcher" app:showAsAction="always|withText"/> <item android:title="设置" android:id="@+id/setting"/> <item android:title="更多操作" > <menu > <item android:title="退出" android:id="@+id/exit"/> <item android:title="子菜单2" /> <item android:title="子菜单3" /> </menu> </item> </menu>