Android 解决沉浸式状态栏下,输入法弹出,布局不会自动调整的BUG

一.前言

在开发中,如果输入框在布局的底部。在弹出输入发时,为了使输入法不遮挡输入框通常有两种做法:
1.将布局压缩(Activity的android:windowSoftInputMode属性设置为”adjustResize”)。
2.移动布局,将布局顶到输入框之上(Activity的android:windowSoftInputMode属性设置为”adjustPan”)

在使用沉浸式状态栏之后,发现将布局压缩的方法没用了(Activity的android:windowSoftInputMode属性设置为”adjustResize”了),但是移动布局的方式还是有用的。

二.解决方法

不知道这是不是Android的一个BUG,找了很多资料,才发现有以下一种解决方法。

1.自定义ViewGroup(LinearLayout,RelativeLayout等),重写fitSystemWindows方法,如下:

public class MyLinearLayout extends LinearLayout {

    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);
    }

    @Override
    protected boolean fitSystemWindows(Rect insets) {
        insets.top = 0;
        return super.fitSystemWindows(insets);
    }
}

2.将原先的xml布局的根ViewGroup换成我们自定义的ViewGroup。

3.在Activity或Fragment中加载出该自定义ViewGroup,然后调用setFitsSystemWindows(true)方法,如下:

MyLinearLayout linearLayout = (MyLinearLayout) findViewById(R.id.activityMain_mRootView);
linearLayout.setFitsSystemWindows(true);

最好在Activity或Fragment销毁时调用linearLayout.setFitsSystemWindows(false);

至此完毕,如有错误,欢迎指教。

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
这个问题涉及到 Android 布局输入法的相关知识。一般情况下,Android 输入法弹出时会将布局顶上去,这是系统自动处理的。但是,如果你想控制这个过程,可以使用 Android 的软键盘监听器来监听输入法弹出和收起事件,然后在代码中根据事件类型来调整布局。具体实现可以参考以下步骤: 1. 在布局文件中,设置 android:windowSoftInputMode 属性为 "adjustResize",这样当输入法弹出时,布局会被自动调整。 2. 创建一个软键盘监听器类,并实现 OnGlobalLayoutListener 接口。 3. 在监听器中重写 onGlobalLayout() 方法,监听输入法弹出和收起事件,并根据事件类型来调整布局。 4. 在 Activity 的 onCreate() 方法中,注册软键盘监听器。 下面是一个示例代码: ``` public class MainActivity extends Activity implements OnGlobalLayoutListener { private View mRootView; private int mHeightDiff = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRootView = findViewById(R.id.root_view); mRootView.getViewTreeObserver().addOnGlobalLayoutListener(this); } @Override public void onGlobalLayout() { Rect r = new Rect(); mRootView.getWindowVisibleDisplayFrame(r); int heightDiff = mRootView.getRootView().getHeight() - (r.bottom - r.top); if (mHeightDiff != heightDiff) { mHeightDiff = heightDiff; if (heightDiff > 100) { // 输入法弹出 // 调整布局 // ... } else { // 输入法收起 // 恢复布局 // ... } } } } ``` 在这个示例中,我们通过监听 onGlobalLayout() 方法来监听输入法弹出和收起事件,并根据 heightDiff 的值来判断当前是否是输入法弹出状态。如果是,我们可以在相应的位置调整布局;如果不是,我们可以恢复布局。注意,heightDiff 的值是根据屏幕的高度计算出来的,单位为像素。具体的调整方法可以根据实际需求来进行编写。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值