前言:
關(guān)于下拉選擇框比默,估計大家都有很多選擇,我在以前的文章:項目需求討論-HyBrid模式需求改造
上寫過下拉框選擇這一塊盆犁,正好用的Spinner命咐。
這次正好又有一個下拉框的需求,所以這次我使用了PopupWindow來實現(xiàn)的谐岁。然后想到其實PopupWindow很多地方都會用到醋奠,但是一直沒有好好的總結(jié)過,所以就想到了寫本文伊佃,而且本文也十分的基礎(chǔ)和簡單窜司,大家也很好理解。
主要分為三部分:
- PopupWindow的使用
- PopupWindow工具類的封裝
- PopupWindow源碼分析
正文
我們知道上來直接給一大串的源碼航揉,很少有人會繼續(xù)看下去塞祈,所以我們就自己先寫個下拉選擇框demo來進行演示。
所以我們可以先來看下我們需要的下拉框樣式:(為了隨便舉個例子帅涂,所以設(shè)計的比較丑):
我們可以一步步來看如何實現(xiàn):
1.基礎(chǔ)使用教程
既然要跳出下面的彈框议薪,而且本文說過要使用PopupWindow,所以就是實現(xiàn)一個PopupWindow即可媳友,十分簡單斯议。
1.1 實例化PopupWindow對象
既然實例化PopupWindow對象,所以我們看下它的構(gòu)造函數(shù):
public PopupWindow() {
this(null, 0, 0);
}
public PopupWindow(View contentView) {
this(contentView, 0, 0);
}
public PopupWindow(int width, int height) {
this(null, width, height);
}
public PopupWindow(View contentView, int width, int height) {
this(contentView, width, height, false);
}
/**
@param contentView the popup content
@param width the popup's width
@param height the popup's height
@param focusable true if the popup can be focused, false otherwise
*/
public PopupWindow(View contentView, int width, int height, boolean focusable) {
if (contentView != null) {
mContext = contentView.getContext();
mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
}
setContentView(contentView);
setWidth(width);
setHeight(height);
setFocusable(focusable);
}
我們可以看到不管你用的哪個構(gòu)造函數(shù)醇锚,最終一定是調(diào)用了最后一個構(gòu)造函數(shù):PopupWindow(View contentView, int width, int height, boolean focusable)
也就是說我們要告訴PopupWindow這些內(nèi)容:
- 顯示的contentView
- PopupWindow要顯示的寬和高哼御,
- PopupWindow是否有獲取焦點的能力(默認false)。
假設(shè)我們用的第四個構(gòu)造函數(shù)
View contentView = LayoutInflater.from(MainActivity.this).inflate(R.layout.popuplayout, null);
PopupWindow popupWindow = new PopupWindow(contentView,ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,true);
1.2 PopupWindow相關(guān)設(shè)置方法
當(dāng)然我們也可以使用第一個構(gòu)造函數(shù)生成對象焊唬,然后通過相應(yīng)的SetXXXX方法恋昼,設(shè)置各種參數(shù)。
我們來看下一些常用的Set方法:
設(shè)置contentView, 寬和高,獲取焦點能力:
popupWindow.setContentView(contentView);
popupWindow.setHeight(height);
popupWindow.setWidth(width);
popupWindow.setFocusable(true);
點擊窗體外消失:
// 需要設(shè)置一下PopupWindow背景求晶,點擊外邊消失才起作用
popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources(),(Bitmap) null));
// 點擊窗外可取消
popupWindow.setTouchable(true);
popupWindow.setOutsideTouchable(true);
關(guān)于窗體會被軟件盤遮擋:
// 設(shè)置pop被鍵盤頂上去焰雕,而不是遮擋
popupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
popupwindow添加各種動畫效果(平移,縮放芳杏,透明等):
popupWindow.setAnimationStyle(R.style.popwindow_anim_style);
動畫的style:
<style name="AnimDown" parent="@android:style/Animation">
<item name="android:windowEnterAnimation">@anim/push_scale_in</item>
<item name="android:windowExitAnimation">@anim/push_scale_out</item>
</style>
具體的動畫:
<!-- 顯示動畫-->
<?xml version="1.0" encoding="utf-8"?><!-- 左上角擴大-->
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="true">
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="200"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:toXScale="1.0"
android:toYScale="1.0" />
</set>
<!-- 隱藏動畫-->
<?xml version="1.0" encoding="utf-8"?><!-- 左上角擴大-->
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="true">
<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="200"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:toXScale="1.0"
android:toYScale="0.001" />
</set>
1.3 PopupWindow顯示出來
主要是使用showXXXX方法來實現(xiàn),而這個方法也有好幾個:
我們先來看showAsDropDown
和showAtLocation
的區(qū)別:
很多人估計用的更多的是showAsDropDown辟宗,它們的最大區(qū)別簡單來說是showAsDropDown是相對于某個控件爵赵,然后PopupWindow顯示在這個控件的下方;而showAtLocation是相對于屏幕泊脐,可以通過設(shè)置Gravity來指定PopupWindow顯示在屏幕的那個位置空幻。
比如我們現(xiàn)在先看showAsDropDown
:
//PopupWindow會顯示我們傳入的這個View的下方,平切是左邊對齊
//(也就是view控件的左下角與popupWindow的左上角對齊)
showAsDropDown(View)
//PopupWindow還是在這個View的下方容客,
//但是額外可以設(shè)置x,y的偏移值秕铛,x,y表示坐標(biāo)偏移量
showAsDropDown(View,int,int);
比如我們代碼寫為:showAsDropDown(View,50,50);X軸和Y軸都偏移了50约郁。
//PopupWindow可以額外設(shè)定Gravity,默認就是Gravity.Left但两。
//同時設(shè)置為Top和Bottom沒啥效果鬓梅,因為是在這個View的下方。
showAsDropDown(View,int,int,int);
比如我們代碼寫為:popupWindow.showAsDropDown(v,0,0,Gravity.RIGHT);變成了View的右下角與PopupWindow的左上角對齊了谨湘。
我們再來看showAtLocation
:
因為這個方法是PopupWindow的顯示相對于屏幕绽快,所以傳入的View也是只要這個屏幕的就可以,因為這個View的傳入也只是為了拿到Window Token紧阔。
//這個方法最后還是等于調(diào)用了另外一個showAtLocation方法,
//傳入view只是為了拿到token
//x,y同樣是x和y軸的偏移值
public void showAtLocation(View parent, int gravity, int x, int y) {
showAtLocation(parent.getWindowToken(), gravity, x, y);
}
public void showAtLocation(IBinder token, int gravity, int x, int y){
.......
}
比如我們寫入的代碼是:popupWindow.showAtLocation(view, Gravity.RIGHT | Gravity.BOTTOM, 0, 0);
如果我們設(shè)置為:popupWindow.showAtLocation(view, Gravity.TOP, 0, 0);
我們發(fā)現(xiàn)PopupWindow并沒有在statusbar的上面坊罢。如果我們想要覆蓋statusbar呢,可以再加一句:popupWindow.setClippingEnabled(false);
所以基本使用估計大家都會了擅耽。我們來總結(jié)下代碼:
1.4 總結(jié)PopupWindow初級使用代碼
LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
//自定義布局
ViewGroup view = (ViewGroup) mLayoutInflater.inflate(R.layout.window, null, true);
PopupWindow popupWindow = new PopupWindow(view, LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT, true);
//是否需要點擊PopupWindow外部其他界面時候消失
mPopWindow.setBackgroundDrawable(new BitmapDrawable());
mPopWindow.setOutsideTouchable(true);
//設(shè)置touchable和focusable
mPopWindow.setFocusable(true);
mPopWindow.setTouchable(true);
/**
然后比如在某個按鈕的點擊事件中顯示PopupWindow
切記不能直接在比如onCreate中直接調(diào)用顯示popupWindow,
會直接拋出異常,原因后面源碼解析會提到
*/
btn.setOnclickListener(v -> {
if (popupWindow != null) {
popupWindow.showAsDropDown(v);
}
})
2.PopupWindow工具類封裝
我在以前寫過Dialog的封裝文章:
項目需求討論-Android 自定義Dialog實現(xiàn)步驟及封裝
我們這次來對PopupWindow來進行封裝活孩,我們還是像上面的文章那樣,使用Builder模式乖仇。
我們先來看我們要注意哪些因素要考慮:
- contentView ,這里有二種可能憾儒,一是用戶只是傳了R.layout.xxx進來,二是用戶傳了具體的View對象進來这敬。
- PopupWindow的寬和高航夺。 (可能需要傳入Px值,可能是dp值崔涂,可能是R.dimen.xxx值,如果不傳入阳掐,就默認為Wrap_Content,也就是會顯示你傳入的contentView的寬高)
- 是否需要顯示動畫,如果需要顯示動畫冷蚂,那么具體的style參數(shù)
- focusable,touchable 的設(shè)置
- 是否設(shè)置點擊外部讓PopupWindow消失
- 設(shè)置里面的某個View的點擊事件
所以初步我們可以寫成這樣:
public class CustomPopupWindow extends PopupWindow {
private CustomPopupWindow(Builder builder) {
super(builder.context);
builder.view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
setContentView(builder.view);
setHeight(builder.height == 0?ViewGroup.LayoutParams.WRAP_CONTENT:builder.height);
setWidth(builder.width == 0?ViewGroup.LayoutParams.WRAP_CONTENT:builder.width);
if (builder.cancelTouchout) {
setBackgroundDrawable(new ColorDrawable(0x00000000));//設(shè)置透明背景
setOutsideTouchable(builder.cancelTouchout);//設(shè)置outside可點擊
}
setFocusable(builder.isFocusable);
setTouchable(builder.isTouchable);
if(builder.animStyle != 0){
setAnimationStyle(builder.animStyle);
}
}
public static final class Builder {
private Context context;
private int height, width;
private boolean cancelTouchout;
private boolean isFocusable = true;
private boolean isTouchable = true;
private View view;
private int animStyle;
public Builder(Context context) {
this.context = context;
}
public Builder view(int resView) {
view = LayoutInflater.from(context).inflate(resView, null);
return this;
}
public Builder view(View resVew){
view = resVew;
return this;
}
public Builder heightpx(int val) {
height = val;
return this;
}
public Builder widthpx(int val) {
width = val;
return this;
}
public Builder heightdp(int val) {
height = dip2px(context, val);
return this;
}
public Builder widthdp(int val) {
width = dip2px(context, val);
return this;
}
public Builder heightDimenRes(int dimenRes) {
height = context.getResources().getDimensionPixelOffset(dimenRes);
return this;
}
public Builder widthDimenRes(int dimenRes) {
width = context.getResources().getDimensionPixelOffset(dimenRes);
return this;
}
public Builder cancelTouchout(boolean val) {
cancelTouchout = val;
return this;
}
public Builder isFocusable(boolean val) {
isFocusable = val;
return this;
}
public Builder isTouchable(boolean val) {
isTouchable = val;
return this;
}
public Builder animStyle(int val){
animStyle = val;
return this;
}
public Builder addViewOnclick(int viewRes, View.OnClickListener listener) {
view.findViewById(viewRes).setOnClickListener(listener);
return this;
}
public CustomPopupWindow build() {
return new CustomPopupWindow(this);
}
}
@Override
public int getWidth() {
return getContentView().getMeasuredWidth();
}
public static int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
}
所以只要知道我們要設(shè)定哪些屬性缭保,就很容易封裝。
然后使用就可以:
customPopupWindow = new CustomPopupWindow.Builder(this)
.cancelTouchout(true)
.view(popupWindowView)
.isFocusable(true)
.animStyle(R.style.AnimDown)
.build();
這里我要額外提上面封裝類代碼中的二個知識點:
知識點1. 提前知道popupwindow的寬高蝙茶。
我們可以看到在我們的工具類中艺骂,有一段代碼:
builder.view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
,
就是把我們傳進去的contentView提前繪制隆夯,這樣我們就可以調(diào)用popupwindow.getContentView().getMeasuredWidth()
方法來獲取這個contentView的寬高了(ps:我們一般設(shè)置的popupwindow的寬高肯定跟我們傳進去的contentview一致)钳恕。
可能有些人就會問了,我們?yōu)樯缎枰崆爸纏opupwindow的寬高呢蹄衷,比如下面這個需求:
比如上面的啟動PopupWindow的按鈕忧额,比下面的選項寬,我們肯定希望咱們的PopupWindow是顯示在正中間愧口,所以我們在調(diào)用:
showAsDropDown(View anchor, int xoff, int yoff);
時候傳入的X值的偏移量就要為上面的按鈕寬度
減去下面PopupWindow的寬度
后的一半睦番。但是平常情況下,我們單純通過PopupWindow.getWidth()
或者contentView.getWidth()
方法,在第一次點擊出現(xiàn)的時候托嚣,獲取到的值前者為-2巩检,后者為0,然后再次點擊的時候就是正確值了示启。因為第一次點擊前兢哭,PopupWindow還沒出現(xiàn)在屏幕過,所以也沒有被繪制出來過丑搔,寬度當(dāng)然也獲取不到準確值了厦瓢。出現(xiàn)過一次后,第二次點擊就能正確獲取了啤月。所以第一次PopupWindow就出現(xiàn)在錯誤位置煮仇,后面就對了。
所以我們重新重載了PopupWindow
的getWidth
方法:
@Override
public int getWidth() {
return getContentView().getMeasuredWidth();
}
知識點2. Touchable和Focusable的設(shè)置
我們一般對上面的按鈕設(shè)置成這樣:
btn.setOnclickListener(v -> {
if (popupWindow != null) {
popupWindow.showAsDropDown(v);
}
})
這樣點擊按鈕后就可以出現(xiàn)我們的PopupWindow,但是你再次點擊這個按鈕谎仲,PopupWindow會先消失浙垫,然后再次出現(xiàn),就像下面這樣:
但是我們希望的是點擊按鈕后,如果PopupWindow在的話就消失郑诺。
當(dāng)然你可以在點擊事件里面用:PopupWindow.isShowing();
判斷夹姥,然后讓PopupWindow.dismiss();
,但是別人用了我們的工具類,總不能還要告訴它要在觸發(fā)按鈕點擊事件里面要額外判斷吧辙诞,所以我們只需要在我們工具類中默認設(shè)置PopupWindow的touchable
和focusable
為true
,這樣辙售,我們的點擊事件啥都不用改,就可以點擊一下出現(xiàn)飞涂,再點擊消失旦部。
3. PopupWindow源碼簡單分析
很慚愧,很早以前就會用PopupWindow较店,但是源碼一直沒有去看過士八。
在講解PopupWindow源碼前我們先來看下其他的知識。
我們應(yīng)該都做過或者看見過添加懸浮窗等功能梁呈,或者在某些文章看見過Window和WindowManager的介紹婚度,比如在《Android藝術(shù)開發(fā)之旅》里面,也有相關(guān)的一章專門講這個官卡,大家可以看下:
Android開發(fā)藝術(shù)探索——第八章:理解Window和WindowManager
假設(shè)我們現(xiàn)在要在應(yīng)用程序的某處加個按鈕蝗茁,應(yīng)該怎么樣呢:
Button btn = new Button(this);
btn.setText("我是窗口");
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
WindowManager.LayoutParams layout = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT
, WindowManager.LayoutParams.WRAP_CONTENT, 0,0,
PixelFormat.TRANSLUCENT);
layout.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
layout.gravity = Gravity.CENTER;
layout.type = WindowManager.LayoutParams.TYPE_APPLICATION;
layout.x = 300;
layout.y = 100;
wm.addView(btn, layout);
只需要通過WindowManager的addView方法,把這個按鈕加進來即可寻咒,我估計有百分之八九十的安卓開發(fā)都大概見過或者知道這種通過WindowManager添加的方式评甜。
我們可以看出有這么幾步:
- 創(chuàng)建了要顯示的ContentView(此處為Button)
- 創(chuàng)建WindowMananger.LayoutParams對象
- 對LayoutParams對象設(shè)置相應(yīng)的屬性值,比如x,y
- WindowMananger對象調(diào)用addView(ContentView,LayoutParams);
PS:這里額外提下layout.type = WindowManager.LayoutParams.TYPE_APPLICATION;這個屬性仔涩,比如我們當(dāng)前只是在我們的app里面加一個按鈕,所以也不需要做其他額外處理粘舟;如果我們是想全局添加按鈕熔脂,也就是我們的app最小化到了后臺佩研,在手機桌面還是能看到有個按鈕懸浮(類似一些手機清理助手等懸浮小球)霞揉,需要切換這里的type屬性旬薯,同時還要聲明相應(yīng)的權(quán)限,不然app就會報錯适秩,說permission denied for this window type绊序。相應(yīng)的type介紹大家可以參考:WindowManager.LayoutParams的type屬性
沒錯,咱們的PopupWindow也是類似的秽荞。
我們從構(gòu)造函數(shù)開始看起來:
public PopupWindow(View contentView, int width, int height, boolean focusable) {
if (contentView != null) {
mContext = contentView.getContext();
mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
}
setContentView(contentView);
setWidth(width);
setHeight(height);
setFocusable(focusable);
}
我們可以看到骤公,果然獲取了WindowManager
對象,然后給PopupWindow的內(nèi)部的contentView、width扬跋、height阶捆、focusable
賦值。
我們看最后顯示的方法源碼:
public void showAsDropDown(View anchor, int xoff, int yoff, int gravity) {
if (isShowing() || mContentView == null) {
return;
}
TransitionManager.endTransitions(mDecorView);
attachToAnchor(anchor, xoff, yoff, gravity);
mIsShowing = true;
mIsDropdown = true;
//'我們可以看到這里果然生成了相應(yīng)的WindowManager.LayoutParams'
final WindowManager.LayoutParams p = createPopupLayoutParams(anchor.getWindowToken());
//'把這個LayoutParams傳過去钦听,把PopupWindow真正的樣子洒试,也就是view創(chuàng)建出來'
preparePopup(p);
//'findDropDownPosition方法確定好PopupWindow要顯示的位置'
final boolean aboveAnchor = findDropDownPosition(anchor, p, xoff, yoff,
p.width, p.height, gravity);
updateAboveAnchor(aboveAnchor);
p.accessibilityIdOfAnchor = (anchor != null) ? anchor.getAccessibilityViewId() : -1;
//'最終調(diào)用windowmanager.addview方法呈現(xiàn)popupwindow'
invokePopup(p);
}
第一步:創(chuàng)建WindowManager.LayoutParams
我們可以看到創(chuàng)建WindowManager.LayoutParams
是通過代碼
final WindowManager.LayoutParams p = createPopupLayoutParams(anchor.getWindowToken());
我們具體來看下這個方法
private WindowManager.LayoutParams createPopupLayoutParams(IBinder token) {
final WindowManager.LayoutParams p = new WindowManager.LayoutParams();
// These gravity settings put the view at the top left corner of the
// screen. The view is then positioned to the appropriate location by
// setting the x and y offsets to match the anchor bottom-left
// corner.
p.gravity = computeGravity();
p.flags = computeFlags(p.flags);
p.type = mWindowLayoutType;
p.token = token;
p.softInputMode = mSoftInputMode;
p.windowAnimations = computeAnimationResource();
if (mBackground != null) {
p.format = mBackground.getOpacity();
} else {
p.format = PixelFormat.TRANSLUCENT;
}
if (mHeightMode < 0) {
p.height = mLastHeight = mHeightMode;
} else {
p.height = mLastHeight = mHeight;
}
if (mWidthMode < 0) {
p.width = mLastWidth = mWidthMode;
} else {
p.width = mLastWidth = mWidth;
}
p.privateFlags = PRIVATE_FLAG_WILL_NOT_REPLACE_ON_RELAUNCH
| PRIVATE_FLAG_LAYOUT_CHILD_WINDOW_IN_PARENT_FRAME;
// Used for debugging.
p.setTitle("PopupWindow:" + Integer.toHexString(hashCode()));
return p;
}
第二步:創(chuàng)建View
我們再看preparePopup(p);
方法:
private void preparePopup(WindowManager.LayoutParams p) {
if (mContentView == null || mContext == null || mWindowManager == null) {
throw new IllegalStateException("You must specify a valid content view by calling setContentView() before attempting to show the popup.");
}
// The old decor view may be transitioning out. Make sure it finishes
// and cleans up before we try to create another one.
if (mDecorView != null) {
mDecorView.cancelTransitions();
}
// When a background is available, we embed the content view within
// another view that owns the background drawable.
/**
'準備backgroundView,因為一般mBackgroundView是null朴上,
所以把之前setContentView設(shè)置的contentView作為mBackgroundView,
不然就生成一個PopupBackgroundView(繼承FrameLayout)垒棋,
把contentView加進去,然后再對這個PopupBackgroundView設(shè)置背景'
*/
if (mBackground != null) {
mBackgroundView = createBackgroundView(mContentView);
mBackgroundView.setBackground(mBackground);
} else {
mBackgroundView = mContentView;
}
/**
'生成相應(yīng)的PopupWindow的根View痪宰。
實際也就是實例一個PopupDecorView(繼承FrameLayout)叼架,然后把contentView add進來
(ps:是不是想起Activity的根view:DecorView,也是叫這個名字,也是把Activity的contentView加進來)'
*/
mDecorView = createDecorView(mBackgroundView);
// The background owner should be elevated so that it casts a shadow.
mBackgroundView.setElevation(mElevation);
// We may wrap that in another view, so we will need to manually specify
// the surface insets.
p.setSurfaceInsets(mBackgroundView, true /*manual*/, true /*preservePrevious*/);
mPopupViewInitialLayoutDirectionInherited =
(mContentView.getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT);
}
第三步:WindowManager.LayoutParams根據(jù)我們的參考View來確定具體屬性值
主要是通過源碼中的下面這個方法:
findDropDownPosition(anchor, p, xoff, yoff,p.width, p.height, gravity);
因為我們可能讓PopupWindow出現(xiàn)在我們點擊按鈕的下面酵镜,所以我們會傳入按鈕的View碉碉,我們知道我們讓PopupWindow出現(xiàn)在按鈕下方,肯定需要設(shè)置WindowManager.LayoutParams的x淮韭,y值垢粮,才能讓它出現(xiàn)在指定位置,所以我們肯定要根據(jù)按鈕的View靠粪,獲取它的x,y值蜡吧,然后額外加上我們后來傳進來的x,y軸的偏移值,然后最后顯示占键。
我們具體查看源碼的內(nèi)容:
private boolean findDropDownPosition(View anchor, WindowManager.LayoutParams outParams,
int xOffset, int yOffset, int width, int height, int gravity) {
final int anchorHeight = anchor.getHeight();
final int anchorWidth = anchor.getWidth();
if (mOverlapAnchor) {
yOffset -= anchorHeight;
}
// Initially, align to the bottom-left corner of the anchor plus offsets.
final int[] drawingLocation = mTmpDrawingLocation;
/**
'我們可以看到調(diào)用了getLocationInWindow方法昔善,
來獲取我們參考的View的當(dāng)前窗口內(nèi)的絕對坐標(biāo),
得到的值為數(shù)組:
location[0] -----> x坐標(biāo)
location[1] -----> y坐標(biāo)'
*/
anchor.getLocationInWindow(drawingLocation);
//'我們的PopupWindow的x為當(dāng)前的參考View的x值加上我們額外傳入的偏移值'
outParams.x = drawingLocation[0] + xOffset;
//'我們的PopupWindow的y為當(dāng)前的參考View的y值加上我們參考view的高度及額外傳入的偏移值'
outParams.y = drawingLocation[1] + anchorHeight + yOffset;
final Rect displayFrame = new Rect();
anchor.getWindowVisibleDisplayFrame(displayFrame);
if (width == MATCH_PARENT) {
width = displayFrame.right - displayFrame.left;
}
if (height == MATCH_PARENT) {
height = displayFrame.bottom - displayFrame.top;
}
// Let the window manager know to align the top to y.
outParams.gravity = computeGravity();
outParams.width = width;
outParams.height = height;
// If we need to adjust for gravity RIGHT, align to the bottom-right
// corner of the anchor (still accounting for offsets).
final int hgrav = Gravity.getAbsoluteGravity(gravity, anchor.getLayoutDirection())
& Gravity.HORIZONTAL_GRAVITY_MASK;
/**
'如果是Gravity.RIGHT,我們的x值還需要再做偏移,
相當(dāng)于減去(我們的PopupWindow寬度減去參考View的寬度)畔乙。'
*/
if (hgrav == Gravity.RIGHT) {
outParams.x -= width - anchorWidth;
}
final int[] screenLocation = mTmpScreenLocation;
anchor.getLocationOnScreen(screenLocation);
// First, attempt to fit the popup vertically without resizing.
final boolean fitsVertical = tryFitVertical(outParams, yOffset, height,
anchorHeight, drawingLocation[1], screenLocation[1], displayFrame.top,
displayFrame.bottom, false);
// Next, attempt to fit the popup horizontally without resizing.
final boolean fitsHorizontal = tryFitHorizontal(outParams, xOffset, width,
anchorWidth, drawingLocation[0], screenLocation[0], displayFrame.left,
displayFrame.right, false);
// If the popup still doesn not fit, attempt to scroll the parent.
if (!fitsVertical || !fitsHorizontal) {
final int scrollX = anchor.getScrollX();
final int scrollY = anchor.getScrollY();
final Rect r = new Rect(scrollX, scrollY, scrollX + width + xOffset,
scrollY + height + anchorHeight + yOffset);
if (mAllowScrollingAnchorParent && anchor.requestRectangleOnScreen(r, true)) {
// Reset for the new anchor position.
anchor.getLocationInWindow(drawingLocation);
outParams.x = drawingLocation[0] + xOffset;
outParams.y = drawingLocation[1] + anchorHeight + yOffset;
// Preserve the gravity adjustment.
if (hgrav == Gravity.RIGHT) {
outParams.x -= width - anchorWidth;
}
}
// Try to fit the popup again and allowing resizing.
tryFitVertical(outParams, yOffset, height, anchorHeight, drawingLocation[1],
screenLocation[1], displayFrame.top, displayFrame.bottom, mClipToScreen);
tryFitHorizontal(outParams, xOffset, width, anchorWidth, drawingLocation[0],
screenLocation[0], displayFrame.left, displayFrame.right, mClipToScreen);
}
// Return whether the popup top edge is above the anchor top edge.
return outParams.y < drawingLocation[1];
}
第三步:WindowManager添加相應(yīng)的View
通過最后的invokePopup(p);
private void invokePopup(WindowManager.LayoutParams p) {
if (mContext != null) {
p.packageName = mContext.getPackageName();
}
final PopupDecorView decorView = mDecorView;
decorView.setFitsSystemWindows(mLayoutInsetDecor);
setLayoutDirectionFromAnchor();
//'最后通過windowmanager的addview方法把decorView加進來'
mWindowManager.addView(decorView, p);
if (mEnterTransition != null) {
decorView.requestEnterTransition(mEnterTransition);
}
}
補充1:當(dāng)然我們平常也知道用WindowManager.removeView或者removeViewImmediate方法移除View君仆,而我們的PopupWindow.dismiss()方法也是一樣,使用了
mWindowManager.removeViewImmediate(decorView);
移除,這步我就不多說了。大家可以自己看下返咱。
補充2:看懂了showAsDropDown的源碼钥庇,showAsLocation的就更簡單了,直接讓LayoutParams的x和y值等于你傳入的x,y值咖摹,其他代碼都是類似的评姨。
補充3:我們前面提過在onCreate方法里面直接顯示ShowAsDropDown等顯示方法會報錯:android.view.WindowManager$BadTokenException,因為這時候Activity的相關(guān)View都沒初始化好萤晴,也就拿到的view.token為null了吐句。
結(jié)語
PopupWindow小結(jié)可能寫的不夠全,或者哪里寫的不對店读,歡迎大家指出嗦枢。