本文介紹了詳解Android中PopupWindow在7.0后適配的解決,分享給大家,具體如下:
這里主要記錄一次踩坑的經(jīng)歷。
需求:如上圖左側(cè)效果,想在按鈕的下方彈一個(gè)PopupWindow。嗯,很簡(jiǎn)單一個(gè)效果,然當(dāng)適配7.0后發(fā)現(xiàn)這個(gè)PopupWindow顯示異常,然后網(wǎng)上找到了下面這種方案。
7.0適配方案(但7.1又復(fù)現(xiàn)了)
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()); } } |
然后我那個(gè)開心啊,然后我就告訴其他人popwindow 在7.0 (SDK=24)適配的問題,然后所有popwindow都這么更改了。
尷尬的是7.1 (SDK=25)上又復(fù)現(xiàn)了這個(gè)問題,顯示異常。
最終解決方案
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())); } |
在初始化的時(shí)候通過動(dòng)態(tài)設(shè)置高度來(lái)完成顯示效果。此時(shí)我們直接調(diào)用顯示就行了。
1
|
mPopupWindow.showAsDropDown(anchor); |
小思考
當(dāng)項(xiàng)目中公用PopupWindow的時(shí)候,你一定想著封裝一次,畢竟PopupWindow的初始化也是一個(gè)體力活。于是,可以將這種適配方案直接在showAsDropDown()方法中實(shí)現(xiàn)。
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); // 重新設(shè)置PopupWindow高度 } super .showAsDropDown(anchor); } ... } |
與上面那種方案比較
- 兩種不同的計(jì)算高度的方法
- 都是通過設(shè)置PopupWindow的高度實(shí)現(xiàn)
- 這種封裝可以簡(jiǎn)化重用代碼
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.jianshu.com/p/df010d92f646