Android_AutoLayout全新适配方式原理分析

1.前言

具体过程,参考文章http://blog.csdn.net/lmj623565791/article/details/49990941


2.实现步骤


(1).初始化

AndroidManifest.xml设置design_width和design_height

AutoLayoutConifg.getInstance().useDeviceSize().init(this);//初始化屏幕信息,得到屏幕宽高和设计宽高


(2).布局文件

//以下布局为例,即可实现自动布局


    

    
    

即可根据上面简单步骤,即可实现自动适配布局。特殊的ListView可以参照库Demo说明


3.原理分析

//以AutoRelativeLayout源码为例
public class AutoRelativeLayout extends RelativeLayout
{
    private final AutoLayoutHelper mHelper = new AutoLayoutHelper(this);
    //...
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        if (!isInEditMode())
            mHelper.adjustChildren();//调整属性值,根据不同设备类型的比例值
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
    //...
}
public class AutoLayoutHelper {
    private final ViewGroup mHost;

    public AutoLayoutHelper(ViewGroup host) {
        mHost = host;
        if (mAutoLayoutConifg == null) {
            initAutoLayoutConfig(host);
        }
    }
    ////调整属性值,根据不同设备类型的比例值
    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);
                }
            }
        }

    }
}
//以调整字号大小为例
public abstract class AutoAttr {
    public void apply(View view) {
        int val;
        if (useDefault()) {
            val = defaultBaseWidth() ? getPercentWidthSize() : getPercentHeightSize();
        	//调整字号大小,getPercentHeightSize()将被执行,执行AutoUtils.getPercentHeightSizeBigger(pxVal)方法
        } else {
            //val = ...
        }

        if (val > 0)
            val = Math.max(val, 1);//val值将被设置
        execute(view, val);//根据属性,设置属性值
    }

    protected int getPercentWidthSize() {
        return AutoUtils.getPercentWidthSizeBigger(pxVal);
    }

    protected int getPercentHeightSize() {
        return AutoUtils.getPercentHeightSizeBigger(pxVal);
    }
}
public class AutoUtils {
    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;
        }
    }
}

你可能感兴趣的:(Android)