Android的對話框有兩種:PopupWindow和AlertDialog。它們的不同點在於:
- AlertDialog的位置固定,而PopupWindow的位置可以隨意
- AlertDialog是非阻塞線程的,而PopupWindow是阻塞線程的
PopupWindow的位置按照有無偏移分,可以分為偏移和無偏移兩種;按照參照物的不同,可以分為相對於某個控件(Anchor錨)和相對於父控件。具體如下
- showAsDropDown(View anchor):相對某個控件的位置(正左下方),無偏移
- showAsDropDown(View anchor, int xoff, int yoff):相對某個控件的位置,有偏移
- showAtLocation(View parent, int gravity, int x, int y):相對於父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以設置偏移或無偏移
/** * 初始化popWindow * */ private void initPopWindow() { View popView = inflater.inflate(R.layout.listview_pop, null); popupWindow = new PopupWindow(popView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); popupWindow.setBackgroundDrawable(new ColorDrawable(0)); //設置popwindow出現和消失動畫 popupWindow.setAnimationStyle(R.style.PopMenuAnimation); btn_pop_close = (ImageView) popView.findViewById(R.id.btn_pop_close); ll_pop_speech=(LinearLayout) popView.findViewById(R.id.ll_pop_speech); ll_pop_favor=(LinearLayout) popView.findViewById(R.id.ll_pop_favor); ll_pop_dislike=(LinearLayout) popView.findViewById(R.id.ll_pop_dislike); btn_pop_close.setOnClickListener(new popItemOnClickListener()); ll_pop_speech.setOnClickListener(new popItemOnClickListener()); ll_pop_favor.setOnClickListener(new popItemOnClickListener()); ll_pop_dislike.setOnClickListener(new popItemOnClickListener()); }
/** * 顯示popWindow * */ public void showPop(View parent, int x, int y,int postion) { //設置popwindow顯示位置 popupWindow.showAtLocation(parent, 0, x, y); //獲取popwindow焦點 popupWindow.setFocusable(true); //設置popwindow如果點擊外面區域,便關閉。 popupWindow.setOutsideTouchable(true); popupWindow.update(); if (popupWindow.isShowing()) { } }
/** * 每個ITEM中more按鈕對應的點擊動作 * **/ public class popAction implements OnClickListener{ int position; public popAction(int position){ this.position = position; } @Override public void onClick(View v) { int[] arrayOfInt = new int[2]; //獲取點擊按鈕的坐標 v.getLocationOnScreen(arrayOfInt); int x = arrayOfInt[0]; int y = arrayOfInt[1]; showPop(v, x , y, position); } }
源碼下載 地址 http://pan.baidu.com/s/1ntJTvol