實例:
創建/res/menu/popupmenu.xml文件, 定義彈出菜單(PopupMenu)的佈局.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:id="@+id/popupmenu">
<item android:id="@+id/menu1"
android:title="item 1"/>
<item android:id="@+id/menu2"
android:title="item 2"/>
<item android:id="@+id/menu3"
android:title="item 3"/>
</group>
</menu>
修改 main.xml 添加一個按鈕啟動彈出菜單.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Button
android:id="@+id/startpopupmenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start PopupMenu"
/>
</LinearLayout>
主Java代碼.
package com.Android3PopupMenu;
import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.PopupMenu;
public class Android3PopupMenuActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonPopupMenu = (Button)findViewById(R.id.startpopupmenu);
buttonPopupMenu.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
PopupMenu popupMenu = new PopupMenu(Android3PopupMenuActivity.this, view);
popupMenu.getMenuInflater().inflate(R.menu.popupmenu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
// Do something...
return true;
}
});
popupMenu.show();
}});
}
}