PopupWindow是一个弹出式窗口,它可以展示任意View。他会浮在当前窗口的上方展示。
下面看代码:
@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); //设置在屏幕中的显示位置
}
}
菜单的布局文件:
android:layout_
android:layout_
android:orientation="horizontal"
>
android:id="@+id/icon_1" android:background="@drawable/icon_1" android:layout_ android:layout_/> android:id="@+id/icon_2" android:background="@drawable/icon_2" android:layout_ android:layout_/> android:id="@+id/icon_3" android:background="@drawable/icon3" android:layout_ android:layout_/> android:id="@+id/icon_4" android:background="@drawable/icon4" android:layout_ android:layout_/>