Android屏幕适配的前世今生(二)

前言

上篇文章介绍了在屏幕适配上遇到的问题,采用px或者dp都会与设计稿存在一定的偏差,也详细的介绍了dpdpi含义和作用,本篇文章着重介绍我们应该如何做好屏幕适配的工作,以及各种屏幕适配方法发展史。

适配的目标

为了解决屏幕适配的难题,网上也不断的涌现出来各种解决方案。我们先整清楚,屏幕适配的核心目标是什么或者说怎么样才算是完美还原的设计稿。

我们还是拿实际开发场景举例子:

假如我们的设计稿以iphone6为标准,屏幕尺寸为4.7英寸,分辨率为750x1334

设计稿中有个控件是宽度是375px,高度667px,视觉效果宽高分别为屏幕宽高的一半,那么我们的目标就是在任何分辨率的手机上,这个控件视觉效果都是这部手机宽度的一半

我们还是以小米9Pixel xl为例:

机型 分辨率 屏幕尺寸 ppi dpi
小米9 1080x2340 6.39英寸 403 440
Pixel xl 1440x2560 5.5英寸 534 560

如果我们完美适配,那么这个控件宽高
小米9上应该分别是540px1170px
Pixel xl上应该是720px1280px

知道我们的目标了,我们再来看看各种适配方案,是怎么做到这点的吧。

dp

初出茅庐时,我们都天真无邪,认为直接使用dpsp作为单位就能万事大吉,实际上面对线上各种奇怪的分辨率,总会跟设计稿有出入,原因上篇文章已经介绍过了。

宽高限定符

宽高限定符是利用Android资源限定符匹配原则,通过指定分辨率,让对应分辨率的手机使用对应资源文件下尺寸值,相当于把设计稿要求的尺寸做了一个简单转换。

      res/
          values/
            dimens.xml 
          values-2340x1080/
            dimens.xml
          values-2560x1440/
            dimens.xml

比如:

小米9上,宽度375px实际上应该转换为 375*1080/750 = 540px, 高度667px实际上应该转换为 667*2340/1334= 1170px

Pixel xl,宽度375px实际上应该转换为 375*1440/750 = 540px, 高度667px实际上应该转换为 667*2560/1334= 1280px

我们在values-2340x1080dimens文件中定义

540px
1170px

我们在values-2560x1440dimens文件中定义

720px
1280px

接着我们在布局文件中宽高分别使用@dimen/px_375,@dimen/y_667

    

那么在2340x10802560x1440两种分辨率手机上,会分别使用不同资源文件中x_375y_667对应的像素。视觉效果都是宽高的一半,这样就能实现完美适配了。

在实际开发中我们怎么操作呢?

  1. 确定设计稿分辨率,作为基准;
  2. 枚举出所有需要适配的分辨率,并创建名为values-分辨率资源文件夹;
  3. 在各分values-分辨率中dimens文件中,通过转换公式,计算每份基准宽高对应的实际像素值。

在布局文件中,我们就可以直接使用x_xxx,y_xxx来自动适配了.

上述的步骤随便写个脚本就可以自动生成, 这里贴一下demo


package cc.wecando.pxadaptergenerator

import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter

data class Size(val width: Int, val height: Int)


class PxAdapterGenerator(val designSize: Size, val adapterSizes: List) {
    fun generate() {
        adapterSizes.forEach {
            val endFix = if (it.height > it.width) {
                "${it.height}x${it.width}"
            } else {
                "${it.width}x${it.height}"
            }
            val dir = File("values-${endFix}")
            if (!dir.exists() || !dir.isDirectory) {
                dir.mkdirs()
            }
            val dimensFile = File(dir, "dimens.xml")
            if (dimensFile.exists()) {
                dimensFile.delete()
            }

            val bufferedWriter = BufferedWriter(FileWriter(dimensFile))
            bufferedWriter.write("""""")
            bufferedWriter.newLine()
            bufferedWriter.write("""    """)
            bufferedWriter.newLine()

            for (i in 1..designSize.width) {
                val px = (i * (it.width.toFloat() / designSize.width) + 0.5f).toInt()
                bufferedWriter.write("""     ${px}px""")
                bufferedWriter.newLine()
            }
            for (i in 1..designSize.height) {
                val px = (i * (it.height.toFloat() / designSize.height) + 0.5f).toInt()
                bufferedWriter.write("""     ${px}px""")
                bufferedWriter.newLine()
            }
            bufferedWriter.write("""     """)
            bufferedWriter.close()
        }

    }
}


fun main() {
    val designSize = Size(750, 1334)
    val adapterSizes = listOf(
        Size(480, 800),
        Size(750, 1334),
        Size(1080, 2340),
        Size(1440, 2560)
    )
    val generator = PxAdapterGenerator(designSize, adapterSizes)
    generator.generate()

}
生成文件结构

该方案的思路就是利用Android宽高限定符匹配策略,把设计稿宽高分成N,M份,N=设计稿宽度M=设计稿高度,枚举出所有分辨率以及对应分辨率下每份对应的px

横向每份对应的px = 手机宽度/设计稿宽度
纵向每份对应的px = 手机高度/设计稿高度

每份在不同分辨率上对应不同的像素值,已达到适配的目的。

是不是看到这里,心里窃喜赶紧试试,其实这种方案问题还是很多的

  1. 需要枚举所有主流分辨率,资源文件不可避免会增大;
  2. 匹配资源文件时,是以DisplayMetricswidthPixelheightPixel为准,而heightPixel是减掉statusBarHeight和navigationBarHeight之后的高度;
  3. 当未匹配到对应分辨率资源文件时的策略是未知的(Android官方并没有明确说明)。

对于第2点,拿小米9为例,分辨率官方参数是2340*1440,但是实际上widthPixel = 1080heightPixel = 2135,正是如此,不可避免又要遇到第3点问题。

对于第3尽管官方没有明确说明,我们还是可以从Android源码里面分析出匹配策略。

frameworks/base/libs/androidfw/ResourceTypes.cpp中找到ResTable_config::isBetterThan方法,当不存在和当前设备分辨率完全一致的资源文件夹时,会取宽高差异值和最小的文件夹,当然,只有分辨率限定符小于等于当前设备分辨率的资源文件夹才参与比较,具体代码如下。

bool ResTable_config::isBetterThan(const ResTable_config& o,
        const ResTable_config* requested) const {
        
        if (screenSize || o.screenSize) {
            // "Better" is based on the sum of the difference between both
            // width and height from the requested dimensions.  We are
            // assuming the invalid configs (with smaller sizes) have
            // already been filtered.  Note that if a particular dimension
            // is unspecified, we will end up with a large value (the
            // difference between 0 and the requested dimension), which is
            // good since we will prefer a config that has specified a
            // size value.
            int myDelta = 0, otherDelta = 0;
            if (requested->screenWidth) {
                myDelta += requested->screenWidth - screenWidth;
                otherDelta += requested->screenWidth - o.screenWidth;
            }
            if (requested->screenHeight) {
                myDelta += requested->screenHeight - screenHeight;
                otherDelta += requested->screenHeight - o.screenHeight;
            }
            if (myDelta != otherDelta) {
                return myDelta < otherDelta;
            }
        }                

该方法定义了资源文件的匹配策略,根据设备的相关信息与应用中存在的资源文件作比较,越在前面的作比较的设备信息,匹配优先级最高。方法的最后,可以看到分辨率属性的匹配策略,这也说明分辨率限定符的匹配优先级是很低的,排在倒数第二。

对于一台languagezh,分辨率是1920x1080的手机,如果我们提供values-zhvalues-1920x1080两个资源文件夹, 那么应用会优先取values-zh中的资源。

扯得有点远了,如果对限定符匹配优先级感兴趣的同学,可以自行研究源码或者参考这篇官方文章

AndroidAutoLayout

直接使用宽高限定符,既麻烦又存在不匹配的问题。我们核心只是需要把布局文件中定义尺寸大小,做一个转换。AndroidAutoLayout就是这样的一个库,在运行时做转换。

我们简要分析下原理。

首先我们在AndroidManifest中定义设计稿的宽高,作为基准。





在编写布局文件时候,我们使用库提供的自定义ViewGroup,譬如AutoLinearLayout

使用自定义的ViewGroup会为每一个子View提供相应的LayoutParams,譬如AutoLinearLayout.LayoutParams

这个LayoutParams会通过AutoLayoutHelper#getAutoLayoutInfo方法收集子View所有跟尺寸相关的属性(比如margin相关的属性,padding相关的属性),并返回mAutoLayoutInfo

public static class LayoutParams extends LinearLayout.LayoutParams
            implements AutoLayoutHelper.AutoLayoutParams
    {
        private AutoLayoutInfo mAutoLayoutInfo;

        public LayoutParams(Context c, AttributeSet attrs)
        {
            super(c, attrs);
            // 收集子View所有跟尺寸相关的属性
            mAutoLayoutInfo = AutoLayoutHelper.getAutoLayoutInfo(c, attrs);
        }

每一个跟尺寸相关的属性会封装成AutoAttr对象,譬如把paddingLeft属性封装成 PaddingLeftAttr,并存放在mAutoLayoutInfoautoAttrs字段中

    private List autoAttrs = new ArrayList<>();
    public static AutoLayoutInfo getAutoLayoutInfo(Context context,
                                                   AttributeSet attrs)
    {

        AutoLayoutInfo info = new AutoLayoutInfo();
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AutoLayout_Layout);
        int baseWidth = a.getInt(R.styleable.AutoLayout_Layout_layout_auto_basewidth, 0);
        int baseHeight = a.getInt(R.styleable.AutoLayout_Layout_layout_auto_baseheight, 0);
        a.recycle();
        TypedArray array = context.obtainStyledAttributes(attrs, LL);
        int n = array.getIndexCount();
        // 收集所有跟尺寸相关的属性
        for (int i = 0; i < n; i++)
        {
            int index = array.getIndex(i);
//            String val = array.getString(index);
//            if (!isPxVal(val)) continue;

            if (!DimenUtils.isPxVal(array.peekValue(index))) continue;

            int pxVal = 0;
            try
            {
                pxVal = array.getDimensionPixelOffset(index, 0);
            } catch (Exception ignore)//not dimension
            {
                continue;
            }
            switch (index)
            { 
                case INDEX_PADDING_LEFT:
                    //  封装成AutoAttr对象,并添加到autoAttrs中
                    info.addAttr(new PaddingLeftAttr(pxVal, baseWidth, baseHeight));
                    break;
            }
        }
        array.recycle();
        L.e(" getAutoLayoutInfo " + info.toString());
        return info;
    }

Android触发绘制流程并到计算控件大小时(onMeasure时),会调用的AutoLayoutHelper#adjustChildren方法:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        if (!isInEditMode())
            mHelper.adjustChildren();
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

AutoLayoutHelper#adjustChildren会取出每一个子viewlayoutParams,如果是自定义ViewGrouplayoutParams,继续调用AutoLayoutInfo#fillAttrs方法。

    public void adjustChildren()
    {
        AutoLayoutConifg.getInstance().checkParams();

        for (int i = 0, n = mHost.getChildCount(); i < n; i++)
        {
            View view = mHost.getChildAt(i);
            ViewGroup.LayoutParams params = view.getLayoutParams();

            if (params instanceof AutoLayoutParams)
            {
                AutoLayoutInfo info =
                        ((AutoLayoutParams) params).getAutoLayoutInfo();
                if (info != null)
                {
                    info.fillAttrs(view);
                }
            }
        }

    }

fillAttr方法其实就是遍历每一个AutoAttr。调用其apply方法:

    public void fillAttrs(View view)
    {
        for (AutoAttr autoAttr : autoAttrs)
        {
            autoAttr.apply(view);
        }
    }

apply方法会将该属性值做适配转换,最终通过execute方法将属性设置为这个适配后的值。

    public void apply(View view)
    {

        boolean log = view.getTag() != null && view.getTag().toString().equals("auto");

        if (log)
        {
            L.e(" pxVal = " + pxVal + " ," + this.getClass().getSimpleName());
        }
        int val;
        if (useDefault())
        {
            val = defaultBaseWidth() ? getPercentWidthSize() : getPercentHeightSize();
            if (log)
            {
                L.e(" useDefault val= " + val);
            }
        } else if (baseWidth())
        {
            val = getPercentWidthSize();
            if (log)
            {
                L.e(" baseWidth val= " + val);
            }
        } else
        {
            val = getPercentHeightSize();
            if (log)
            {
                L.e(" baseHeight val= " + val);
            }
        }

        if (val > 0)
            val = Math.max(val, 1);//for very thin divider
        execute(view, val);
    }

apply中是怎么做转换的呢,首先判断是以宽还是高作为基准,比如像paddingLeftpaddingRight肯定是以宽度为基准了,paddingTop,paddingBottom肯定是以高度为基准。 拿宽度基准为例子,跟踪一下方法调用链,最终会调用getPercentWidthSizeBigger方法。

getPercentWidthSize->AutoUtils.getPercentWidthSizeBigger

    public static int getPercentWidthSizeBigger(int val)
    {
        int screenWidth = AutoLayoutConifg.getInstance().getScreenWidth();
        int designWidth = AutoLayoutConifg.getInstance().getDesignWidth();

        int res = val * screenWidth;
        if (res % designWidth == 0)
        {
            return res / designWidth;
        } else
        {
            return res / designWidth + 1;
        }

    }

AutoLayoutConifg.getInstance().getDesignWidth()获取在AndroidManifest中定义的设计稿宽度

AutoLayoutConifg.getInstance().getScreenWidth()获取我们设备的widthPixel

假如我们在布局文件中定义paddingLeft20px,在小米9上就会转换为
20 * 1080 / 750 + 1 = 29px

设计稿上,20/750 = 2.7%
小米9上 ,29/1080 = 2.7%
视觉上就跟设计稿保持一致了。
本打算一篇把所有适配方案介绍完的,无奈分析AndroidAutoLayout占用了太多篇幅,剩下的方案就放到下篇吧。

我们记住所有方案的核心就是将布局文件中设置的尺寸,通过各种手段,转换为合适的尺寸,以达到在各种分辨率的手机上,视觉效果与设计稿保持一致。

你可能感兴趣的:(Android屏幕适配的前世今生(二))