问题描述:项目中有一个类似微信的聊天界面,底部有一个editText需要根据输入法的高度进行动态适配,将输入框显示在输入法之上。
当前实现方式是如下

       mContentView = activity.findViewById(android.R.id.content);
        mContentView.setOnApplyWindowInsetsListener((v, insets) -> {
            // 获取输入法高度(IME)
            int imeBottomInset = insets.getInsets(WindowInsets.Type.ime()).bottom;

            // 设置 View 的 Padding,确保内容避开刘海和输入法
//            mContentView.setPadding(0, safeTopInset, 0, imeBottomInset);
            if (mFragmentViewRef.get()!=null){
                mFragmentViewRef.get().setPadding(0, 0, 0, imeBottomInset);
            }
            // 输入法已收起时调整 Fragment 的焦点
            if (imeBottomInset < 200) {
                if (mFragmentViewRef.get() != null) {
                    mFragmentViewRef.get().setFocusableInTouchMode(true);
                    mFragmentViewRef.get().requestFocus();
                }
            }
            return insets;
        });

这种方法原先是没有问题的,但是聊天页面使用的是fragment,依附在游戏的主Activity,而游戏在未与我充分沟通的情况下,直接在主activity中加入了如下代码块,适配android 15上的全面屏问题。

    private void setupEdgeToEdge() {
        if (android.os.Build.VERSION.SDK_INT >= 35) {
            View rootView = findViewById(android.R.id.content);
            rootView.setBackgroundColor(0xFF000000); // 设置黑色背景
            ViewCompat.setOnApplyWindowInsetsListener(rootView, (v, insets) -> {
                Log.d("ImeTest",TAG + "setOnApplyWindowInsetsListener inner call");
                DisplayCutoutCompat cutout = insets.getDisplayCutout();
                int notchHeight = (cutout != null) ? cutout.getSafeInsetTop() : 0;
                // 根据刘海高度调整,保留上方空间
                v.setPadding(0, notchHeight, 0, 0);
                return WindowInsetsCompat.CONSUMED;
            });
        }
    }

游戏的主Activity中在onCreate和onResume中调用这两个方法,而fragment之后onCreate的时候调用的设置listener,这导致了选择图片的时候跳出应用,然后返回的时候会走Activity onresume的方法,然后走fragment的onResume,这就导致了,activity的listener生效的,而fragment的并没有生效。
解决方法1:在不让使用方改动的情况下
在聊天页面fragment中的onResume重新设置一下listener
解决方法2,需要游戏页面改动
在聊天页面fragment中使用自己页面布局的根view,而不是系统窗口的根view,另外需要游戏setupEdgeToEdge不返回WindowInsetsCompat.CONSUMED;,而是向子view继续传递WindowInsets。

Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐