場景描述
因爲在xml中加載佈局時,使用了ViewStub.需要加載的佈局中有EditText.導致 延遲加載
方法嘗試
- AndroidManifest.xml 裏配置android:windowSoftInputMode=“adjustResize|stateHidden”
- onCreate方法中setContentView之前添加getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
- 在根佈局文件中加入:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:fillViewport="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> </LinearLayout> </ScrollView>
嘗試後均均無效。應該是我動態添加的佈局,導致檢測不到鍵盤改變了佈局顯示的大小。思路是監測鍵盤彈出,再計算顯示的大小,是否需要頂起佈局。
借鑑了:https://blog.csdn.net/u010231682/article/details/93479895
解決方式:引入代碼監聽軟鍵盤,同時在根佈局添加ScrollView
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
public class LayoutAutoResizeHelper {
private int usableHeightPrevious;
private LayoutAutoResizeHelper() {
}
public static LayoutAutoResizeHelper getInstance() {
return InstanceHolder.INSTANCE;
}
private static class InstanceHolder {
private static final LayoutAutoResizeHelper INSTANCE = new LayoutAutoResizeHelper();
}
public void adjustResize(Activity activity) {
setupAdjustResize(activity);
}
private void setupAdjustResize(Activity activity) {
ViewGroup content = activity.findViewById(android.R.id.content);
View contentView = content.getChildAt(0);
contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
possiblyResizeChildOfContent(contentView);
}
});
}
private void possiblyResizeChildOfContent(View contentView) {
ViewGroup.LayoutParams contentViewParams = contentView.getLayoutParams();
//獲取當前界面可視區域(注:可視區域指APP界面)
Rect rect = computeUsableRect(contentView);
//獲取當前界面可視區域高度
int currentUsableHeight = rect.bottom - rect.top;
if (currentUsableHeight != usableHeightPrevious) {
//獲取根佈局高度
int rootViewHeight = contentView.getRootView().getHeight();
//計算出根佈局高度與可視區域高度差值
int heightDiff = rootViewHeight - currentUsableHeight;
//差值超過四分之一說明軟鍵盤彈出
if (heightDiff > (rootViewHeight / 4)) {
//全屏模式需要加上狀態欄高度,否則低於軟鍵盤高度的輸入框彈起時與軟鍵盤頂部會有偏差
contentViewParams.height = rootViewHeight - heightDiff + getStatusHeight(contentView.getContext());
} else {
//此處需要使用rect.bottom ,因爲部分手機有虛擬導航且處於開啓狀態時會導致底部界面被虛擬導航遮擋
contentViewParams.height = rect.bottom;
}
contentView.requestLayout();
usableHeightPrevious = currentUsableHeight;
}
}
private Rect computeUsableRect(View view) {
Rect r = new Rect();
view.getWindowVisibleDisplayFrame(r);
return r;
}
private int getStatusHeight(Context context) {
return StatusBarUtil.getStatusBarHeight(context);//獲取狀態欄高度,根據項目修改補充,這裏就不貼出來了
}
}