屏幕适配【自定义像素适配、百分比布局适配、修改像素密度】

2019-10-14  本文已影响0人  瑜小贤

屏幕适配常见方式

布局适配

图片资源适配

用户流程匹配

限定符适配

刘海屏适配

自定义像素适配

以一个特定宽高尺寸的设备为参考,在View的加载过程,根据当前设备的实际像素,换算出目标像素,再作用在控件上。

public class PixUtils {
    private static PixUtils utils;

    //设计稿参考的宽高
    private static final float STANDARD_WIDTH = 1080;
    private static final float STANDARD_HEIGHT = 1920;

    //这里是屏幕显示宽高
    private int mDisplayWidth;
    private int mDisplayHeight;

    private PixUtils(Context context){
        //获取屏幕的宽高
        if(mDisplayWidth == 0 || mDisplayHeight == 0){
            WindowManager manager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
            if(manager != null){
                DisplayMetrics displayMetrics = new DisplayMetrics();
                manager.getDefaultDisplay().getMetrics(displayMetrics);
                if(displayMetrics.widthPixels > displayMetrics.heightPixels){
                    //横屏
                    mDisplayWidth = displayMetrics.heightPixels;
                    mDisplayHeight = displayMetrics.widthPixels;
                }else{
                    mDisplayWidth = displayMetrics.widthPixels;
                    mDisplayHeight = displayMetrics.heightPixels - getStatusBarHeight(context);
                }

            }

        }
    }


    public static PixUtils getInstance(Context context){
        if(utils == null){
            synchronized (PixUtils.class){
                if(utils == null){
                    utils = new PixUtils(context.getApplicationContext());
                }
            }
        }
        return utils;
    }


    //获得水平方向上的缩放比例
    public float getHorizontalScale(){
        return mDisplayWidth / STANDARD_WIDTH;
    }

    //获得垂直方向上的缩放比例
    public float getVerticalScale(){
        return mDisplayHeight / STANDARD_HEIGHT;
    }

    public static int getStatusBarHeight(Context context){
        int resId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if(resId > 0){
            return context.getResources().getDimensionPixelSize(resId);
        }
        return 0;
    }

}

自定义view 并重写onMeasure

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){
    if(!flag){
            float scaleX = PixUtils.getInstance(getContext()).getHorizontalScale();
            float scaleY = PixUtils.getInstance(getContext()).getVerticalScale();

            int count = getChildCount();
            for (int i = 0; i < count; i++) {
                View child = getChildAt(i);
                LayoutParams params = (LayoutParams) child.getLayoutParams();

                params.width = (int) (params.width * scaleX);
                params.height = (int) (params.height * scaleY);
                params.leftMargin = (int) (params.leftMargin * scaleX);
                params.rightMargin = (int) (params.rightMargin * scaleX);
                params.topMargin = (int) (params.topMargin * scaleY);
                params.bottomMargin = (int) (params.bottomMargin * scaleY);
            }
            flag = true;
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

布局文件,布局的大小及边距等设置需用像素px 且 不用改变

<com.bard.gplearning.widget.ScreenAdaptLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
    <TextView 
      android:layout_width = "540px"
      android:layout_height = "540px"
      android:alignParentTop="true"
      android:alignParentLeft="true"
      android:text="hello world">
</com.bard.gplearning.widget.ScreenAdaptLayout>

百分比布局适配

以父容器尺寸作为参考,在View的加载过程,根据当前父容器实际尺寸换算出目标尺寸,再作用在View上。不需要知道设计规范的尺寸是多少,但须知道控件占父容器/屏幕的比例。
google在'com.android.support:percent:28.0.0'中提供了PercentRelativeLayout等布局文件,虽然已经过时了,但是还能用,现在都被ConstraintLayout代替了。

public class PercentLayout extends RelativeLayout {
    public PercentLayout(Context context) {
        super(context);
    }

    public PercentLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public PercentLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //获取父容器的尺寸
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            ViewGroup.LayoutParams params = child.getLayoutParams();
            if(checkLayoutParams(params)){
                LayoutParams lp = (LayoutParams) params;


                float widthPercent = lp.widthPercent;
                float heightPercent = lp.heightPercent;
                float marginLeftPercent = lp.marginLeftPercent;
                float marginRightPercent = lp.marginRightPercent;
                float marginTopPercent = lp.marginTopPercent;
                float marginBottomPercent = lp.marginBottomPercent;
                
                if(widthPercent > 0){
                    params.width = (int) (widthSize * widthPercent);
                }

                if(heightPercent > 0){
                    params.height = (int) (heightSize * heightPercent);
                }


                if(marginLeftPercent > 0){
                    lp.leftMargin = (int) (lp.leftMargin * marginLeftPercent);
                }

                if(marginRightPercent > 0){
                    lp.rightMargin = (int) (lp.rightMargin * marginRightPercent);
                }


                if(marginTopPercent > 0){
                    lp.topMargin = (int) (lp.topMargin * marginTopPercent);
                }

                if(marginBottomPercent > 0){
                    lp.bottomMargin = (int) (lp.bottomMargin * marginBottomPercent);
                }
            }
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }


    @Override
    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
        return p instanceof LayoutParams;
    }

    @Override
    public RelativeLayout.LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new LayoutParams(getContext(), attrs);
    }

    public static class LayoutParams extends RelativeLayout.LayoutParams {

        private float widthPercent;
        private float heightPercent;
        private float marginLeftPercent;
        private float marginRightPercent;
        private float marginTopPercent;
        private float marginBottomPercent;

        public LayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
            //解析自定义View属性
            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.PercentLayout);
            widthPercent = a.getFloat(R.styleable.PercentLayout_widthPercent, 0);
            heightPercent = a.getFloat(R.styleable.PercentLayout_heightPercent, 0);
            marginLeftPercent = a.getFloat(R.styleable.PercentLayout_marginLeftPercent, 0);
            marginRightPercent = a.getFloat(R.styleable.PercentLayout_marginRightPercent, 0);
            marginTopPercent = a.getFloat(R.styleable.PercentLayout_marginTopPercent, 0);
            marginBottomPercent = a.getFloat(R.styleable.PercentLayout_marginBottomPercent, 0);
            a.recycle();
        }
    }
}

修改像素密度

修改density,scaleDensity,densityDpi值,直接更改系统内部对于目标尺寸而言的像素密度。
先解释下各种名词

可以将setDensity方法运用于自定义的BaseActivity即可
也可以在BaseApplication的onCreate中,在registerActivityLifecycleCallbacks的onActivityCreated回调中调用Density.setDensity。

public class Density {
    private static float appDensity; //表示屏幕密度
    private static float appScaleDensity; //表示字体缩放比例,默认appDensity
    
    private static final float WIDTH = 360; //参考设备的宽,单位是dp 如果设置一个控件为屏幕宽度一半 则为180dp
    
    //需要在setContentView之前调用
    public static void setDensity(Application application, Activity activity){
        //获取当前app的屏幕显示信息
        DisplayMetrics displayMetrics = application.getResources().getDisplayMetrics();
        if(appDensity == 0){
            //初始化赋值操作
            appDensity = displayMetrics.density;
            appScaleDensity = displayMetrics.scaledDensity;
        }
        
        //计算目标值 density,scaleDensity,densityDpi
        float targetDensity = displayMetrics.widthPixels / WIDTH; // 1080/360=3
        float targetScaleDensity = targetDensity * (appScaleDensity / appDensity);
        int targetDensityDpi = (int)(targetDensity * 160);
        
        //替换Activity的density scaleDensity,densityDpi
        DisplayMetrics dm = activity.getResources().getDisplayMetrics();
        dm.density = targetDensity;
        dm.scaledDensity = targetScaleDensity;
        dm.densityDpi = targetDensityDpi;
    }
}
上一篇下一篇

猜你喜欢

热点阅读