自定义DialogFragment显示位置、动画中心异常问题

自定义DialogFragment显示位置、动画中心异常问题,第1张

自定义DialogFragment显示位置、动画中心异常问题

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录
  • 前言
  • 一、想要实现的效果
  • 二、部分关键代码
  • 二、遇到的问题
    • 1.d窗显示的位置Y轴位置始终偏下
    • 2.d窗缩放动画中心异常


前言

最近在自定义Dialog时,遇到一些显示方面问题,记录一下备忘

一、想要实现的效果

想要实现的效果是,点击一个图标按钮,在图标正上方以缩放动画显示d窗。基本原理就是,点击按钮时,通过View.getLocationOnScreen(int[])方法,获取View在屏幕上的位置。然后在Dialog中通过WindowManager.LayoutParams的x、y属性修改d窗显示位置。

二、部分关键代码

透明d窗样式

  
        @android:color/holo_green_light
        @null
        true
        true
        true
        true
        @null
        @style/DialogScaleInOut
    
     
     
        @anim/dialog_scale_in
        @anim/dialog_scale_out
    

Dialog使用的DialogFragment,重写onCreateDialog方法

 public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {

        Dialog dialog = new Dialog(getContext(), R.style.baseDialog);
        dialog.setContentView(R.layout.dialog_frag);

        dialog.getWindow().setWindowAnimations(R.style.DialogScaleInOut);
        WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();

        attributes.gravity = Gravity.TOP | Gravity.START;
        attributes.x = mLocation[0];
        attributes.y = mLocation[1];
        LogUtils.d("DialogGame.onCreateDialog, set window location, x:%s, y:%s", mLocation[0], mLocation[1]);

        dialog.getWindow().setAttributes(attributes);
        // initView(dialog);
        return dialog;
    }
二、遇到的问题 1.d窗显示的位置Y轴位置始终偏下

黄色的d窗的Window.LayoutParam的x、y是直接使用的showDialog的屏幕位置,但显示却并没有上部对齐。

多次测试后,发现是View.getLocationOnScreen(int[])获取到的时绝对的位置,相对整个屏幕左上角,包括了状态栏。但 WindowManager.LayoutParams的x、y,应该是相对了Window的,未包括状态栏,受主题样式影响,android:windowNoTitle为false时,甚至更为偏下。

``

2.d窗缩放动画中心异常

d窗进入Scale动画如下,显示的问题是缩放的中心并不是底部中心,而是很奇怪一个点。



    

最后测试发现,是受主题样式影响,修改Dialog样式父类为android:Theme.Dialog后,动画中心恢复正常。猜测Theme.AppCompat.Dialog中有设置背景相关的东西,影响了Window显示区域,使中心点计算出现偏差。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5660735.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存