1、屏幕适配
原因:安卓设备碎片化,导致app的界面元素在不同的屏幕尺寸上显示不一致。
目的:让布局,布局组件,资源,用户界面流程,匹配不同屏幕尺存。
2、屏幕适配-自定义View
原理:以一个特定宽度尺寸的设备为参考,在View的加载过程,根据当前设备的实际像素换算出目标像素,在作用在控件上。
1、首先需要得到一个缩放比例
如何获取缩放比例呢?
需要获取当前手机的宽和高,在与我们设计稿的参考宽高做比。
public class Utils {
private static Utils utils;
//这里是设计稿参考宽高
private static final float STANDARD_WIDTH = 1080;
private static final float STANDARD_HEIGHT = 1920;
//这里是屏幕显示宽高
private int mDisplayWidth;
private int mDisplayHeight;
private Utils(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 int getStatusBarHeight(Context context){
int resID = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resID > 0){
return context.getResources().getDimensionPixelSize(resID);
}
return 0;
}
public static Utils getInstance(Context context){
if (utils == null){
utils = new Utils(context.getApplicationContext());
}
return utils;
}
//获取水平方向的缩放比例
public float getHorizontalScale(){
return mDisplayWidth / STANDARD_WIDTH;
}
//获取垂直方向的缩放比例
public float getVerticalScale(){
return mDisplayHeight / STANDARD_HEIGHT;
}
}
2、自定义View,在绘制的时候计算出目标像素
public class ScreenAdapterRelativeLayout extends RelativeLayout {
private boolean flag;
public ScreenAdapterLayout(Context context) {
super(context);
}
public ScreenAdapterLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ScreenAdapterLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (!flag){
float scaleX = Utils.getInstance(getContext()).getHorizontalScale();//获取横向缩放比
float scaleY = Utils.getInstance(getContext()).getVerticalScale();//获取竖向缩放比
int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);//重新设置子View的布局属性,在进行View的测量
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);
}
}








网友评论