android教程之使用popupwindow创建菜单示例
本文导语: PopupWindow是一个弹出式窗口,它可以展示任意View。他会浮在当前窗口的上方展示。 下面看代码: 代码如下:public class MyActivity extends Activity{ private PopupWindow menu; private LayoutInflater inflater; private View layout; @Override...
PopupWindow是一个弹出式窗口,它可以展示任意View。他会浮在当前窗口的上方展示。
下面看代码:
public class MyActivity extends Activity{
private PopupWindow menu;
private LayoutInflater inflater;
private View layout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//实例化PopupWindow创建菜单
initMenu();
}
//判断按键 菜单的显示与隐藏
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(!menu.isShowing()&&keyCode == KeyEvent.KEYCODE_MENU){
show();
}else{
menu.dismiss();
}
if(keyCode == KeyEvent.KEYCODE_BACK&&menu.isShowing()){
menu.dismiss();
}
return true;
}
//实例化PopupWindow创建菜单
private void initMenu(){
//获取LayoutInflater实例
inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
//获取弹出菜单的布局
layout = inflater.inflate(R.layout.menu,null);
//设置popupWindow的布局
menu = new PopupWindow(layout, WindowManager.LayoutParams.WRAP_CONTENT,WindowManager.LayoutParams.WRAP_CONTENT);
}
//显示菜单
private void show(){
//设置位置
menu.showAtLocation(this.findViewById(R.id.main), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,0,0); //设置在屏幕中的显示位置
}
}
菜单的布局文件: