Android使用PopupWindow创建一个简单的菜单

openkk 13年前

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); //设置在屏幕中的显示位置            }        }  

菜单的布局文件:

<?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="horizontal"          >      <ImageView          android:id="@+id/icon_1"          android:background="@drawable/icon_1"          android:layout_width="40dp"          android:layout_height="40dp"/>      <ImageView          android:id="@+id/icon_2"          android:background="@drawable/icon_2"          android:layout_width="40dp"          android:layout_height="40dp"/>      <ImageView          android:id="@+id/icon_3"          android:background="@drawable/icon3"          android:layout_width="40dp"          android:layout_height="40dp"/>      <ImageView          android:id="@+id/icon_4"          android:background="@drawable/icon4"          android:layout_width="40dp"          android:layout_height="40dp"/>    </LinearLayout>