沒圖說個X曲聂,先上效果圖
再來個布局圖
紅框部分即我們需要保持在軟鍵盤上方的部分着绊,藍框部分是父布局
1.聲明?LayoutChangeListener
ViewTreeObserver.OnGlobalLayoutListenermLayoutChangeListener =new ViewTreeObserver.OnGlobalLayoutListener() {
????@Override
? ? public void onGlobalLayout() {
????????Rect rect =new Rect();
? ? ? ? final View decorView = getActivity().getWindow().getDecorView();
? ? ? ? decorView.getWindowVisibleDisplayFrame(rect);
? ? ? ? //計算出可見屏幕的高度
? ? ? ? int displayHight = rect.bottom - rect.top;
? ? ? ? //獲得屏幕整體的高度
? ? ? ? int hight = decorView.getHeight();
? ? ? ? //獲得鍵盤高度
? ? ? ? int keyboardHeight = hight - displayHight;
? ? ? ? boolean visible = (double) displayHight / hight <0.7;
? ? ? ? //如果屏幕高度和Window可見區(qū)域高度差值大于整個屏幕高度的0.7嚷辅,則表示軟鍵盤顯示中,否則軟鍵盤為隱藏狀態(tài)颠印。
? ? ? ? if (visible) {
????????????// bottomView 需要跟隨軟鍵盤移動的布局畔塔,上面提到的紅色布局
? ? ? ? ? ? // setDuration(0) 默認300, 設(shè)置 0 ,表示動畫執(zhí)行時間為0所袁,沒有過程盏档,只有動畫結(jié)果了
? ? ? ? ? ? //-keyboardHeight +100這個看手機設(shè)置,一般不需要+100
? ? ? ? ? ? bottomView.animate().translationY(-keyboardHeight +100).setDuration(0).start();
? ? ? ? }else {
????????????bottomView.animate().translationY(0).start();
? ? ? ? }
}
};
2.傳入初始化后的Edittext
private void showInputManager(EditText editText) {?
?/**
?* OnGlobalLayoutListener?
?* 每次布局變化時都會調(diào)用?
?* 界面view 顯示消失都會調(diào)用纲熏,軟鍵盤顯示與消失時都調(diào)用?
?* */?
?constraintLayout.getViewTreeObserver().addOnGlobalLayoutListener(mLayoutChangeListener); InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
constraintLayout是上面提到的藍色部分妆丘,也就是父布局
3.注意事項
如果功能沒實現(xiàn),請檢查一下項目清單文件AndroidManifest.xml中是否有
android:configChanges="orientation|keyboardHidden|screenSize"等設(shè)置局劲,如果有先去掉在看效果勺拣。
如還有其他疑問可以評論區(qū)留言,樓主看到后會及時回復(fù)鱼填。