dismiss() 关闭菜单
package com.qianfengpopmenu;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.Toast;
public class MainActivity extends Activity implements OnMenuItemClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//点点击按钮时弹出弹出菜单
public void showPop(View view){
//创建弹出菜单对象
PopupMenu popupMenu=new PopupMenu(MainActivity.this, view);
//将指定的菜单布局进行加载
getMenuInflater().inflate(R.menu.main, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(this);//给菜单绑定监听
//展示菜单
popupMenu.show();
}
//当popupmenu中某一项被点击时回调该方法
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
Toast.makeText(MainActivity.this, item.getTitle(), Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return false;
}
}
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
<item
android:id="@+id/action_about"
android:orderInCategory="100"
android:showAsAction="never"
android:title="关于"/>
</menu>