输入法遮盖 EditText 问题
修复弹框不能被顶上去的问题: AndroidBug5497Workaround,
原代码在部分手机上会有底部导航栏被遮盖的问题,下面的代码可兼容华为、小米,三星等机型。
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| import android.app.Activity; import android.graphics.Rect; import android.os.Build; import android.view.View; import android.widget.FrameLayout;
public class AndroidBug5497Workaround { public static void assistActivity(Activity activity) { new AndroidBug5497Workaround(activity); }
private View mChildOfContent; private int usableHeightPrevious; private FrameLayout.LayoutParams frameLayoutParams; private int contentHeight; private boolean isfirst = true; private Activity activity; private int statusBarHeight;
private AndroidBug5497Workaround(Activity activity) { int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android"); statusBarHeight = activity.getResources().getDimensionPixelSize(resourceId); this.activity = activity; FrameLayout content = (FrameLayout) activity.findViewById(android.R.id.content); mChildOfContent = content.getChildAt(0);
mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(() -> { if (isfirst) { contentHeight = mChildOfContent.getHeight(); isfirst = false; } possiblyResizeChildOfContent(); });
frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams(); }
private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
if (usableHeightNow != usableHeightPrevious) { int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight(); int heightDifference = usableHeightSansKeyboard - usableHeightNow; if (heightDifference > (usableHeightSansKeyboard / 4)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { frameLayoutParams.height = usableHeightSansKeyboard - heightDifference + statusBarHeight; } else { frameLayoutParams.height = usableHeightSansKeyboard - heightDifference; } } else { frameLayoutParams.height = contentHeight; }
mChildOfContent.requestLayout(); usableHeightPrevious = usableHeightNow; } }
private int computeUsableHeight() { Rect r = new Rect(); mChildOfContent.getWindowVisibleDisplayFrame(r); return (r.bottom - r.top); } }
|
使用方式
1 2 3 4
| setContentView(R.layout.xxx); AndroidBug5497Workaround.assistActivity(this);
|
参考资料