直接使用坐标布局存在不同屏幕位置及大小差异, 即使以dp值也会存在偏差
原因:以dp值方式, 它是按长度进行等比缩放, 也就是说不管x,y,长宽,都是这个比例.在屏幕长宽比不等的情况下, 就会出现偏差
解决:高度按高度比例进行修改, 包括Y方向的 margin,padding,及height等
上代码:
public void autoSuitViews()
{
//默认10寸屏DP尺寸
float W = 1920;
float H = 1200;
// 获取屏幕尺寸
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
float screenWidth = (float)displayMetrics.widthPixels;
float screenHeight = (float)displayMetrics.heightPixels;
float scaleX = screenWidth/W;
float scaleY = screenHeight/H;
View rootView = getWindow().getDecorView().getRootView();
ArrayList<View> allSubviews = getAllChildViews(rootView);
for (View v : allSubviews){
Object tagObj = v.getTag();
int tag = 0;
if (tagObj instanceof String) {
String tagStr = (String)tagObj;
tag = Integer.parseInt(tagStr);
} else {
if((v instanceof ImageView)) //图片不要过滤
tag = 99;
else
continue;
}
//只调整特定视图
if (((tag<=0) || (tag>=100))) continue;
// 获取该视图的布局参数
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
// 设置Margin值(以像素为单位)
int left = (int)(params.leftMargin);
int top = (int)(params.topMargin/scaleX*scaleY);
int right = (int)(params.rightMargin);
int bottom = (int)(params.bottomMargin);
if(params.width<=0 || params.height<=0) continue; //低版本部分视图没给定尺寸默认为负
params.width = (int)(params.width);
params.height = (int)(params.height/scaleX*scaleY);
params.setMargins(left, top, right, bottom);
// 将修改后的布局参数应用于该视图
v.setLayoutParams(params);
//pading设置
int pLeft = v.getPaddingLeft();
int pRight = v.getPaddingRight();
int pTop = (int)(v.getPaddingTop()/scaleX*scaleY);
int pBottom = (int)(v.getPaddingBottom()/scaleX*scaleY);
v.setPadding(pLeft, pTop, pRight, pBottom);
}
}
public static ArrayList<View> getAllChildViews(View view) {
ArrayList<View> allChildViews = new ArrayList<>();
if (view instanceof ViewGroup) {
ViewGroup vp = (ViewGroup) view;
for (int i = 0; i < vp.getChildCount(); i++) {
View child = vp.getChildAt(i);
allChildViews.add(child);
allChildViews.addAll(getAllChildViews(child));
}
}
return allChildViews;
}