软键盘弹出时 EditText 固定在键盘上方

本文介绍了一种在Fragment中实现软键盘弹出时布局自动调整的方法。通过监听全局布局变化,动态设置内容视图的底部内边距,确保输入框不会被软键盘遮挡。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考资料: https://blog.youkuaiyun.com/qq_26665903/article/details/52026732

找了很久才找到一个合适的解决方案, 于是怒赞了一波原作者, 并且为本博客又摘录(抄?)了一篇优秀的博客回来. 啊哈哈…

因为我的需求是在 Fragment 中使用这种效果, 所以代码与原作者代码有些区别. mActivity 来自当前 Fragment.getActivity(), 新手请知悉.

在这里插入图片描述

先在清单文件中为该页面的activity加入这个属性:

   android:windowSoftInputMode="adjustPan|stateHidden"

下面贴下代码 :

View decorView = mActivity.getWindow().getDecorView();
View contentView = mActivity.findViewById(Window.ID_ANDROID_CONTENT);
decorView.getViewTreeObserver().addOnGlobalLayoutListener(getGlobalLayoutListener(decorView, contentView));
        
private ViewTreeObserver.OnGlobalLayoutListener getGlobalLayoutListener(final View decorView, final View contentView) {
        return new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                decorView.getWindowVisibleDisplayFrame(r);

                int height = decorView.getContext().getResources().getDisplayMetrics().heightPixels;
                int diff = height - r.bottom;

                if (diff != 0) {
                    if (contentView.getPaddingBottom() != diff) {
                        contentView.setPadding(0, 0, 0, diff);
                    }
                } else {
                    if (contentView.getPaddingBottom() != 0) {
                        contentView.setPadding(0, 0, 0, 0);
                    }
                }
            }
        };
    }
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值