Android开发中用到软键盘时会出现设置Activity的windowSoftInputMode="adjustResize"失效的问题,这时我们可以在activity的根布局上添加fitsSystemWindows="true",然后adjustResize属性就会起作用。但是这样做还有一个问题,我们的Actionbar会下移一段距离,这段距离的高度相当于状态栏的高度。那么我们该如何解决这个问题,完美使用android adjustresize属性呢?
解决这个问题我们需要自定义一个layout做我们的根布局,在layout中重写fitSystemWindows()和onApplyWindowInsets()方法,具体如下:
public class MyLinearLayout extends LinearLayout{
private int[] mInsets = new int[4];
public MyLinearLayout(Context context) {
super(context);
}
public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public MyLinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected final boolean fitSystemWindows(Rect insets) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// Intentionally do not modify the bottom inset. For some reason,
// if the bottom inset is modified, window resizing stops working.
// TODO: Figure out why.
mInsets[0] = insets.left;
mInsets[1] = insets.top;
mInsets[2] = insets.right;
insets.left = 0;
insets.top = 0;
insets.right = 0;
}
return super.fitSystemWindows(insets);
}
@Override
public final WindowInsets onApplyWindowInsets(WindowInsets insets) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
mInsets[0] = insets.getSystemWindowInsetLeft();
Log.e("mInsets[0]",""+mInsets[0]);
mInsets[1] = insets.getSystemWindowInsetTop();
Log.e("mInsets[1]",""+mInsets[1]);
mInsets[2] = insets.getSystemWindowInsetRight();
Log.e("mInsets[2]",""+mInsets[2]);
return super.onApplyWindowInsets(insets.replaceSystemWindowInsets(0, 0, 0,
insets.getSystemWindowInsetBottom()));
} else {
return insets;
}}}
经过以上的操作之后,就可以很完美的解决windowSoftInputMode="adjustResize"无效问题了,分享就到这里,如果对大家有所帮助,请继续关注我们,我们会持续更新更多优质技术文章!
热点新闻