本文介紹了詳解Android中PopupWindow在7.0后適配的解決,分享給大家,具體如下:
這里主要記錄一次踩坑的經歷。
需求:如上圖左側效果,想在按鈕的下方彈一個PopupWindow。嗯,很簡單一個效果,然當適配7.0后發現這個PopupWindow顯示異常,然后網上找到了下面這種方案。
7.0適配方案(但7.1又復現了)
1
2
3
4
5
6
7
8
9
10
11
12
|
// 將popupWindow顯示在anchor下方 public void showAsDropDown(PopupWindow popupWindow, View anchor) { if (Build.VERSION.SDK_INT < 24 ) { popupWindow.showAsDropDown(anchor); } else { // 適配 android 7.0 int [] location = new int [ 2 ]; // 獲取控件在屏幕的位置 anchor.getLocationOnScreen(location); popupWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, 0 , location[ 1 ] + anchor.getHeight()); } } |
然后我那個開心啊,然后我就告訴其他人popwindow 在7.0 (SDK=24)適配的問題,然后所有popwindow都這么更改了。
尷尬的是7.1 (SDK=25)上又復現了這個問題,顯示異常。
最終解決方案
1
2
3
4
5
6
7
8
9
10
11
|
if (Build.VERSION.SDK_INT < 24 ) { mPopupWindow = new FixedPopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); } else { int [] location = new int [ 2 ]; // 獲取控件在屏幕的位置 anchor.getLocationOnScreen(location); int screenHeight = getScreenHeightPixels(context); mPopupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.MATCH_PARENT, screenHeight - (location[ 1 ] + anchor.getHeight())); } |
在初始化的時候通過動態設置高度來完成顯示效果。此時我們直接調用顯示就行了。
1
|
mPopupWindow.showAsDropDown(anchor); |
小思考
當項目中公用PopupWindow的時候,你一定想著封裝一次,畢竟PopupWindow的初始化也是一個體力活。于是,可以將這種適配方案直接在showAsDropDown()方法中實現。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
import android.graphics.Rect; import android.os.Build; import android.view.View; import android.widget.PopupWindow; /** * Created by smart on 2018/5/15. */ public class FixedPopupWindow extends PopupWindow { public FixedPopupWindow(View contentView, int width, int height){ super (contentView, width, height); } ..... @Override public void showAsDropDown(View anchor) { if (Build.VERSION.SDK_INT >= 24 ) { Rect rect = new Rect(); anchor.getGlobalVisibleRect(rect); // 以屏幕 左上角 為參考系的 int h = anchor.getResources().getDisplayMetrics().heightPixels - rect.bottom; //屏幕高度減去 anchor 的 bottom setHeight(h); // 重新設置PopupWindow高度 } super .showAsDropDown(anchor); } ... } |
與上面那種方案比較
- 兩種不同的計算高度的方法
- 都是通過設置PopupWindow的高度實現
- 這種封裝可以簡化重用代碼
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.jianshu.com/p/df010d92f646