場景:
1、軟件盤擋住了edittext框了,這個必須處理。
2、雖然設置了edittext的軟鍵盤屬性android:windowSoftInputMode="adjustPan"使得軟鍵盤不阻擋edittext,但是為了提高用戶體驗,想把下面的button也顯示出來
3、登錄界面,輸入用戶名時,由於框子較高,不需要移動。當用戶點擊密碼輸入框時才讓view上移。也就是自由控制頁面要不要隨軟鍵盤的彈出而上移。
針對以上三個場景的統一解決方案:(參照了別人的博客,地址找不到了,實在不好意思。添加了靜態控制falg和動態獲取系統底部導航高度的代碼,原博文是寫成了固定值100,在高分辨率的機器上不起作用,原因是分辨率高的機器,底部導航欄比100大,比如我的華為mate8,導航欄高度是108)
細節說明:目前很多機器可以控制底部導航欄隱藏,隱藏后,獲取到的導航欄高度就為0了。
/** * Created by Administrator on 2017/3/11. */ public class SoftInputUtil { // 控制是否移動布局。比如只有密碼輸入框獲取到焦點時才執行。 public static boolean flag=true; /** * @param act activiry用於獲取底部導航欄高度。 * @param root 最外層布局,需要調整的布局 * @param scrollToView 被鍵盤遮擋的scrollToView,滾動root,使scrollToView在root可視區域的底部 */ public static void controlKeyboardLayout(Context act, final View root, final View scrollToView) { final int navigationBarHeight = getNavigationBarHeight(act); root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { Rect rect = new Rect(); //獲取root在窗體的可視區域 root.getWindowVisibleDisplayFrame(rect); //獲取root在窗體的不可視區域高度(被其他View遮擋的區域高度) int rootInvisibleHeight = root.getRootView().getHeight() - rect.bottom; //若不可視區域高度大於100,則鍵盤顯示 if (rootInvisibleHeight > navigationBarHeight&&flag) { int[] location = new int[2]; //獲取scrollToView在窗體的坐標 scrollToView.getLocationInWindow(location); //計算root滾動高度,使scrollToView在可見區域 int srollHeight = (location[1] + scrollToView.getHeight()) - rect.bottom; if (root.getScrollY() != 0) {// 如果已經滾動,要根據上次滾動,重新計算位置。 srollHeight += root.getScrollY(); } root.scrollTo(0, srollHeight); } else { //鍵盤隱藏 root.scrollTo(0, 0); } } }); } /** * 獲取底部導航欄高度 * @param act * @return */ private static int getNavigationBarHeight(Context act) { Resources resources = act.getResources(); int resourceId = resources.getIdentifier("navigation_bar_height","dimen", "android"); int height = resources.getDimensionPixelSize(resourceId); Log.v("dbw", "Navi height:" + height); return height; } }
