Android自定义Layout子类实现屏幕适配原理

本文介绍了在Android11及更高版本中获取系统通知栏高度的方法,以及如何根据屏幕方向调整布局尺寸,同时提供了自定义布局的onMeasure方法,以实现视口缩放功能。
摘要由CSDN通过智能技术生成

1.获取系统通知栏高度  Android11以后不能通过反射调用非公开的API,获取方式:

 /**
     * 获取状态栏高度
     * @return
     */
    private int getValue2() {
        int statusHeight = 0;
        int resourceId = this.context.getResources().getIdentifier("status_bar_height", "dimen",
                "android");
        if (resourceId > 0) {
            statusHeight = this.context.getResources().getDimensionPixelSize(resourceId);
        }
        Log.e("TAG", "getValue2: height --->" + statusHeight );
        return statusHeight;
    }

2.获取WindowManage之后,判断是横屏还是竖屏 横屏需要处理一下, 竖屏直接减掉系统状态栏高度:

  if (displayMetrics.widthPixels > displayMetrics.heightPixels) {
                //横屏
                displayMetricsWidth = displayMetricsHeight;
                displayMetricsHeight = displayMetrics.widthPixels - systemBarHeight;
            } else {
                //竖屏
                displayMetricsWidth = (float) displayMetrics.widthPixels;
                displayMetricsHeight = (float) displayMetrics.heightPixels - systemBarHeight;

            }
3.获取缩放比例 ,当前测试屏幕大小为1920 * 1080像素
    private float STANDRD_WIDTH = 1080F;
    private float STANDRD_HEIGHT = 1920F;
   
    public float getHorValue() {
        return ((float) displayMetricsWidth) / STANDRD_WIDTH;
    }


    public float getVerValue() {
        return ((float) displayMetricsHeight) / (STANDRD_HEIGHT - getSystemBarHeight(context));
    }
 4.自定义布局,继承RelativeLaoyut/LinearLayout 重写onMeasure,获取布局里的每个组件乘上缩放比例
 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        float scaleX = UIUtils.getInstance(getContext()).getHorValue();
        float scaleY = UIUtils.getInstance(getContext()).getVerValue();
        int childCount = this.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childAt = this.getChildAt(i);
            LayoutParams layoutParams = (LayoutParams) childAt.getLayoutParams();
            layoutParams.width = (int) (layoutParams.width * scaleX);
            layoutParams.height = (int) (layoutParams.height * scaleX);
            layoutParams.leftMargin = (int) (layoutParams.leftMargin * scaleX);
            layoutParams.rightMargin = (int) (layoutParams.rightMargin * scaleX);
            layoutParams.topMargin = (int) (layoutParams.topMargin * scaleX);
            layoutParams.bottomMargin = (int) (layoutParams.bottomMargin * scaleX);
        }
    }

 代码实现仅供参考原理

效果图:

  • 7
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值