1.获取系统通知栏高度 Android11以后不能通过反射调用非公开的API,获取方式:
/**
* 获取状态栏高度
* @return
*/
private int getValue2() {
int statusHeight = 0;
int resourceId = this.context.getResources().getIdentifier("status_bar_height", "dimen",
"android");
if (resourceId > 0) {
statusHeight = this.context.getResources().getDimensionPixelSize(resourceId);
}
Log.e("TAG", "getValue2: height --->" + statusHeight );
return statusHeight;
}
2.获取WindowManage之后,判断是横屏还是竖屏 横屏需要处理一下, 竖屏直接减掉系统状态栏高度:
if (displayMetrics.widthPixels > displayMetrics.heightPixels) {
//横屏
displayMetricsWidth = displayMetricsHeight;
displayMetricsHeight = displayMetrics.widthPixels - systemBarHeight;
} else {
//竖屏
displayMetricsWidth = (float) displayMetrics.widthPixels;
displayMetricsHeight = (float) displayMetrics.heightPixels - systemBarHeight;
}
3.获取缩放比例 ,当前测试屏幕大小为1920 * 1080像素
private float STANDRD_WIDTH = 1080F;
private float STANDRD_HEIGHT = 1920F;
public float getHorValue() {
return ((float) displayMetricsWidth) / STANDRD_WIDTH;
}
public float getVerValue() {
return ((float) displayMetricsHeight) / (STANDRD_HEIGHT - getSystemBarHeight(context));
}
4.自定义布局,继承RelativeLaoyut/LinearLayout 重写onMeasure,获取布局里的每个组件乘上缩放比例
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
float scaleX = UIUtils.getInstance(getContext()).getHorValue();
float scaleY = UIUtils.getInstance(getContext()).getVerValue();
int childCount = this.getChildCount();
for (int i = 0; i < childCount; i++) {
View childAt = this.getChildAt(i);
LayoutParams layoutParams = (LayoutParams) childAt.getLayoutParams();
layoutParams.width = (int) (layoutParams.width * scaleX);
layoutParams.height = (int) (layoutParams.height * scaleX);
layoutParams.leftMargin = (int) (layoutParams.leftMargin * scaleX);
layoutParams.rightMargin = (int) (layoutParams.rightMargin * scaleX);
layoutParams.topMargin = (int) (layoutParams.topMargin * scaleX);
layoutParams.bottomMargin = (int) (layoutParams.bottomMargin * scaleX);
}
}
代码实现仅供参考原理
效果图: