import android.app.Application;
import android.content.ComponentCallbacks;
import android.content.res.Configuration;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
public class LayoutAdaption {
private static float sNonCompatDensity;
private static float sNonCompatScaledDensity;
public static void setCustomDensity(@NonNull AppCompatActivity activity, @NonNull final Application application) {
DisplayMetrics metrics = application.getResources().getDisplayMetrics();
if(0 == sNonCompatDensity) {
sNonCompatDensity = metrics.density;
sNonCompatScaledDensity = metrics.scaledDensity;
application.registerComponentCallbacks(new ComponentCallbacks() {
@Override
public void onConfigurationChanged(Configuration newConfig) {
if(null != newConfig && newConfig.fontScale > 0) {
sNonCompatScaledDensity = application.getResources().getDisplayMetrics().scaledDensity;
}
}
@Override
public void onLowMemory() {
}
});
}
final float targetDensity = metrics.widthPixels / 750f;
final float targetScaledDensity = targetDensity * (sNonCompatScaledDensity / sNonCompatDensity);
final int targetDensityDpi = (int) (160 * targetDensity);
metrics.density = targetDensity;
metrics.scaledDensity = targetScaledDensity;
metrics.densityDpi = targetDensityDpi;
DisplayMetrics activityMetrics = activity.getResources().getDisplayMetrics();
activityMetrics.density = targetDensity;
activityMetrics.scaledDensity = targetScaledDensity;
activityMetrics.densityDpi = targetDensityDpi;
}
}
原文地址 https://mp.weixin.qq.com/s/d9QCoBP6kV9VSWvVldVVwA
网友评论