1、布局统一用LinearLayout通过比重控制布局大小;
2、适配器对item布局进行手动设置大小;
3、对话框手动设置外框大小;
4、文字一律需要手动设置大小;
5、19以下统一全屏,19或以上统一使用沉浸式
/**
* 宽度适配
* @param width 设计图宽度,如1280
* @return 宽度缩放比例
*/
public static float getWidthSizeScale(Activity activity, float width) {
DisplayMetrics metric = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
float screenWidth = metric.widthPixels; // 屏幕宽度(像素)
if (metric.heightPixels > screenWidth) {
screenWidth = getHasVirtualKey(activity);
}
return screenWidth / width;
}
/**
* 高度适配
* @param height 设计图高度:如800
* @return 高度缩放比例
*/
public static float getHeightSizeScale(Activity activity, float height) {
DisplayMetrics metric = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
float screenWidth = metric.widthPixels; // 屏幕宽度(像素)
float screenHeight = getHasVirtualKey(activity);
if (metric.heightPixels > screenWidth) {
screenHeight = metric.widthPixels;
}
return screenHeight / height;
}
/**
* 通过反射,获取包含虚拟键的整体屏幕高度
*/
private static int getHasVirtualKey(Activity activity) {
int dpi = 0;
Display display = activity.getWindowManager().getDefaultDisplay();
DisplayMetrics dm = new DisplayMetrics();
@SuppressWarnings("rawtypes")
Class c;
try {
c = Class.forName("android.view.Display");
@SuppressWarnings("unchecked")
Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
method.invoke(display, dm);
dpi = dm.heightPixels;
} catch (Exception e) {
e.printStackTrace();
}
return dpi;
}
/**
* 文字适配
*/
public static float getTextScale(Activity activity) {
DisplayMetrics metric = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(metric);
float widthPixels = metric.widthPixels;
float densityDpi = metric.densityDpi;
if (metric.heightPixels > widthPixels) {
widthPixels = metric.heightPixels;
}
return widthPixels / densityDpi / 5;
}
沉浸式设置
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 沉浸式退出监听
getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(
new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
initWindow();
}
});
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus){
initWindow();
}
}
private void initWindow() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
);
}
}