弹出菜单popupmenu就是点击某个组件时弹出的菜单。
Activity类:
package com.zzj.ui.popupmenudemo; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.PopupMenu; import android.widget.PopupMenu.OnMenuItemClickListener; import android.widget.Toast; import com.zzj.ui.R; public class PopupMenuActivity extends Activity { PopupMenu popupMenu; Menu menu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.popupmenu_activity); popupMenu = new PopupMenu(this, findViewById(R.id.popupmenu_btn)); menu = popupMenu.getMenu(); // 通过代码添加菜单项 menu.add(Menu.NONE, Menu.FIRST + 0, 0, "复制"); menu.add(Menu.NONE, Menu.FIRST + 1, 1, "粘贴"); // 通过XML文件添加菜单项 MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.popupmenu, menu); // 监听事件 popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.news: Toast.makeText(PopupMenuActivity.this, "新建", Toast.LENGTH_LONG).show(); break; case R.id.open: Toast.makeText(PopupMenuActivity.this, "打开", Toast.LENGTH_LONG).show(); break; case Menu.FIRST + 0: Toast.makeText(PopupMenuActivity.this, "复制", Toast.LENGTH_LONG).show(); break; case Menu.FIRST + 1: Toast.makeText(PopupMenuActivity.this, "粘贴", Toast.LENGTH_LONG).show(); break; default: break; } return false; } }); } public void popupmenu(View v) { popupMenu.show(); } }Activity布局文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/popupmenu_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="popupmenu" android:text="弹出菜单" /> </LinearLayout>popupmenu布局文件:
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/news" android:title="新建"/> <item android:id="@+id/open" android:title="打开"/> </menu>效果: