原文:
http://www.cnblogs.com/mengdd/p/3569127.html
Android PopupWindow的使用和分析
PopupWindow使用
PopupWindow這個類用來實現一個彈出框,可以使用任意布局的View作為其內容,這個彈出框是懸浮在當前activity之上的。
PopupWindow使用Demo
這個類的使用,不再過多解釋,直接上代碼吧。
比如彈出框的布局:
彈出框布局
Activity的布局中只有一個按鈕,按下后會彈出框,Activity代碼如下:
packagecom.example.hellopopupwindow;importandroid.os.Bundle;importandroid.app.Activity;importandroid.content.Context;importandroid.util.Log;importandroid.view.LayoutInflater;importandroid.view.MotionEvent;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.view.View.OnTouchListener;importandroid.view.ViewGroup.LayoutParams;importandroid.widget.Button;importandroid.widget.PopupWindow;importandroid.widget.Toast;publicclassMainActivityextendsActivity {privateContext mContext =null;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext=this;
Button button=(Button) findViewById(R.id.button);
button.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View view) {
showPopupWindow(view);
}
});
}privatevoidshowPopupWindow(View view) {//一個自定義的布局,作為顯示的內容View contentView =LayoutInflater.from(mContext).inflate(
R.layout.pop_window,null);//設置按鈕的點擊事件Button button =(Button) contentView.findViewById(R.id.button1);
button.setOnClickListener(newOnClickListener() {
@OverridepublicvoidonClick(View v) {
Toast.makeText(mContext,"button is pressed",
Toast.LENGTH_SHORT).show();
}
});finalPopupWindow popupWindow =newPopupWindow(contentView,
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,true);
popupWindow.setTouchable(true);
popupWindow.setTouchInterceptor(newOnTouchListener() {
@OverridepublicbooleanonTouch(View v, MotionEvent event) {
Log.i("mengdd", "onTouch : ");returnfalse;//這里如果返回true的話,touch事件將被攔截//攔截后 PopupWindow的onTouchEvent不被調用,這樣點擊外部區域無法dismiss}
});//如果不設置PopupWindow的背景,無論是點擊外部區域還是Back鍵都無法dismiss彈框//我覺得這里是API的一個bugpopupWindow.setBackgroundDrawable(getResources().getDrawable(
R.drawable.selectmenu_bg_downward));//設置好參數之后再showpopupWindow.showAsDropDown(view);
}
}
彈出框的布局中有一個TextView和一個Button,Button點擊后顯示Toast,如圖:
第一次實現的時候遇到了問題,就是彈出框不會在按下Back鍵的時候消失,點擊彈框外區域也沒有正常消失,搜索了一下,都說只要設置背景就好了。
然后我就找了個圖片,果然彈框能正常dismiss了(見注釋)。
PopupWindow源碼分析
為了解答一下上面的問題,看看源碼(最新API Level 19,Android 4.4.2)。
1.顯示方法
顯示提供了兩種形式:
showAtLocation()顯示在指定位置,有兩個方法重載:
publicvoidshowAtLocation(View parent,intgravity,intx,inty)publicvoidshowAtLocation(IBinder token,intgravity,intx,inty)
showAsDropDown()顯示在一個參照物View的周圍,有三個方法重載:
publicvoidshowAsDropDown(View anchor)publicvoidshowAsDropDown(View anchor,intxoff,intyoff)publicvoidshowAsDropDown(View anchor,intxoff,intyoff,intgravity)
最后一種帶Gravity參數的方法是API 19新引入的。
彈出的方法中首先需要preparePopup(),最后再invokePopup()。
prepare的方法中可以看到有無背景的分別:
/***
Prepare the popup by embedding in into a new ViewGroup if the
* background drawable is not null. If embedding is required, the layout
* parameters' height is mnodified to take into account the background's
* padding.
*
*@paramp the layout parameters of the popup's content view*/privatevoidpreparePopup(WindowManager.LayoutParams p) {if(mContentView ==null|| mContext ==null|| mWindowManager ==null) {thrownewIllegalStateException("You must specify a valid content view by "? ? ? ? ? ? ? ? ? ? + "calling setContentView() before attempting to show the popup.");
}if(mBackground !=null) {finalViewGroup.LayoutParams layoutParams =mContentView.getLayoutParams();intheight =ViewGroup.LayoutParams.MATCH_PARENT;if(layoutParams !=null&&layoutParams.height==ViewGroup.LayoutParams.WRAP_CONTENT) {
height=ViewGroup.LayoutParams.WRAP_CONTENT;
}//when a background is available, we embed the content view//within another view that owns the background drawablePopupViewContainer popupViewContainer =newPopupViewContainer(mContext);
PopupViewContainer.LayoutParams listParams=newPopupViewContainer.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, height
);
popupViewContainer.setBackgroundDrawable(mBackground);
popupViewContainer.addView(mContentView, listParams);
mPopupView=popupViewContainer;
}else{
mPopupView=mContentView;
}
mPopupViewInitialLayoutDirectionInherited=(mPopupView.getRawLayoutDirection()==View.LAYOUT_DIRECTION_INHERIT);
mPopupWidth=p.width;
mPopupHeight=p.height;
}
2.背景是否為空對Touch事件的影響
如果有背景,則會在contentView外面包一層PopupViewContainer之后作為mPopupView,如果沒有背景,則直接用contentView作為mPopupView。
而這個PopupViewContainer是一個內部私有類,它繼承了FrameLayout,在其中重寫了Key和Touch事件的分發處理:
@OverridepublicbooleandispatchKeyEvent(KeyEvent event) {if(event.getKeyCode() ==KeyEvent.KEYCODE_BACK) {if(getKeyDispatcherState() ==null) {returnsuper.dispatchKeyEvent(event);
}if(event.getAction() ==KeyEvent.ACTION_DOWN&& event.getRepeatCount() == 0) {
KeyEvent.DispatcherState state=getKeyDispatcherState();if(state !=null) {
state.startTracking(event,this);
}returntrue;
}elseif(event.getAction() ==KeyEvent.ACTION_UP) {
KeyEvent.DispatcherState state=getKeyDispatcherState();if(state !=null&& state.isTracking(event) && !event.isCanceled()) {
dismiss();returntrue;
}
}returnsuper.dispatchKeyEvent(event);
}else{returnsuper.dispatchKeyEvent(event);
}
}
@OverridepublicbooleandispatchTouchEvent(MotionEvent ev) {if(mTouchInterceptor !=null&& mTouchInterceptor.onTouch(this, ev)) {returntrue;
}returnsuper.dispatchTouchEvent(ev);
}
@OverridepublicbooleanonTouchEvent(MotionEvent event) {finalintx = (int) event.getX();finalinty = (int) event.getY();if((event.getAction() ==MotionEvent.ACTION_DOWN)&& ((x < 0) || (x >= getWidth()) || (y < 0) || (y >=getHeight()))) {
dismiss();returntrue;
}elseif(event.getAction() ==MotionEvent.ACTION_OUTSIDE) {
dismiss();returntrue;
}else{returnsuper.onTouchEvent(event);
}
}
由于PopupView本身并沒有重寫Key和Touch事件的處理,所以如果沒有包這個外層容器類,點擊Back鍵或者外部區域是不會導致彈框消失的。
補充Case: 彈窗不消失,但是事件向下傳遞
如上所述:
設置了PopupWindow的background,點擊Back鍵或者點擊彈窗的外部區域,彈窗就會dismiss.
相反,如果不設置PopupWindow的background,那么點擊back鍵和點擊彈窗的外部區域,彈窗是不會消失的.
那么,如果我想要一個效果,點擊外部區域,彈窗不消失,但是點擊事件會向下面的activity傳遞,比如下面是一個WebView,我想點擊里面的鏈接等.
研究了半天,說是要給Window設置一個Flag,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
看了源碼,這個Flag的設置與否是由一個叫mNotTouchModal的字段控制,但是設置該字段的set方法被標記為@hide。
所以要通過反射的方法調用:
/*** Set whether this window is touch modal or if outside touches will be sent
* to
* other windows behind it.
**/publicstaticvoidsetPopupWindowTouchModal(PopupWindow popupWindow,booleantouchModal) {if(null==popupWindow) {return;
}
Method method;try{
method= PopupWindow.class.getDeclaredMethod("setTouchModal",boolean.class);
method.setAccessible(true);
method.invoke(popupWindow, touchModal);
}catch(Exception e) {
e.printStackTrace();
}
}
然后在程序中:
UIUtils.setPopupWindowTouchModal(popupWindow,false);
該popupWindow外部的事件就可以傳遞給下面的Activity了。
Reference
http://developer.android.com/reference/android/widget/PopupWindow.html