android 弹出菜单
<!-- 定义基础布局LinearLayout --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical"> <!-- 定义TextView控件 --> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="请按键盘物理菜单键,弹出选项菜单" /> </LinearLayout>
package com.example.yanlei.yl2; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; //导入必备的包 public class MainActivity extends AppCompatActivity { //定义Menu中每个菜单选项的Id private final static int Menu_1 = Menu.FIRST; private final static int Menu_2 = Menu.FIRST + 1; private final static int Menu_3 = Menu.FIRST + 2; private final static int Menu_4 = Menu.FIRST + 3; private final static int Menu_5 = Menu.FIRST + 4; private final static int Menu_6 = Menu.FIRST + 5; private final static int Menu_7 = Menu.FIRST + 6; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 调用父类的onCreate方法 // 通过setContentView方法设置当前页面的布局文件为activity_main setContentView(R.layout.activity_main); } //创建Menu菜单的回调方法 public boolean onCreateOptionsMenu(Menu m) { //参数m就是拿到的当前Activity菜单对象 //想要给当前页面添加方法的话就add进去即可 //add方法的参数:add(分组id,itemid, 排序, 菜单文字) m.add(0, Menu_1, 0, "编辑模式"); m.add(0, Menu_2, 0, "修改壁纸"); m.add(0, Menu_3, 0, "全局搜索"); m.add(0, Menu_4, 0, "桌面缩略图"); m.add(0, Menu_5, 0, "桌面效果"); m.add(0, Menu_6, 0, "系统设置"); m.add(0, Menu_7, 0, "用户信息"); return super.onCreateOptionsMenu(m); } //Menu菜单选项的选项选择的回调事件 public boolean onOptionsItemSelected(MenuItem item) { //参数为用户选择的菜单选项对象 //根据菜单选项的id来执行相应的功能 switch (item.getItemId()) { case 1: Toast.makeText(this, "你点击了编辑模式选项", Toast.LENGTH_SHORT).show(); break; case 2: Toast.makeText(this, "你点击了修改壁纸", Toast.LENGTH_SHORT).show(); break; case 3: Toast.makeText(this, "你点击了全局搜索", Toast.LENGTH_SHORT).show(); break; case 4: Toast.makeText(this, "你点击了桌面缩略图", Toast.LENGTH_SHORT).show(); break; case 5: Toast.makeText(this, "你点击了桌面效果", Toast.LENGTH_SHORT).show(); break; case 6: Toast.makeText(this, "你点击了系统设置", Toast.LENGTH_SHORT).show(); break; case 7: Toast.makeText(this, "你点击了用户信息", Toast.LENGTH_SHORT).show(); break; } return super.onOptionsItemSelected(item); } // 选项菜单关闭时的回调方法 public void onOptionsMenuClosed(Menu menu) { Log.e("onOptionsMenuClosed","用户菜单关闭了"); } // 菜单显示之前的回调方法 public boolean onPrepareOptionsMenu(Menu menu) { Log.e("onPrepareOptionsMenu","用户菜单准备好被显示了"); //方法返回true,就会显示Menu,否则Menu不会被显示 return true; } }