解决在PT屏幕适配方案(今日头条屏幕适配)的项目中使用webview UI错乱问题

在上一篇博文中,介绍了PT适配方案,不了解的可查看Android屏幕适配简单总结,PT适配方案

在使用此适配方案之后,如果项目中没有使用到webview,则没有什么问题,但是,如果你在项目中加入了webview,则你的项目的UI适配会时好时坏。

根本原因:

查找了好久之后在这篇博文中发现了问题:头条屏幕适配问题汇总及解决,这次你值得尝试

在使用适配方案的项目中使用webView会density 复原,原因是由于 WebView 初始化的时候会还原 density 的值导致适配失效。

解决方法:

自定义webview,在webview的构造方法中按照我们的适配方法计算宽,而不要让webview是那原始屏幕的宽去计算

/**
 * 此webView为了解决适配问题、在使用适配方案的项目中使用webView会density 复原,原因是由于 WebView 初始化的时候会还原 density 的值导致适配失效
 * Created by Administrator on 2018/11/10.
 */

public class MyWebView extends WebView {
    private static final int DESIGN_WIDTH = 375;
    private Context mContext;
    public MyWebView(Context context) {
        super(context);
        mContext=context;
        CardDoctorApplication.getInstance().resetDensity(mContext,DESIGN_WIDTH);
    }

    @Override
    public void setOverScrollMode(int mode) {
        super.setOverScrollMode(mode);

    }
}
/**
 * 以pt为单位重新计算大小
 */
public static void resetDensity(Context context, float designWidth) {
    if (context == null)
        return;
    Point size = new Point();
    ((WindowManager) context.getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getSize(size);
    Resources resources = context.getResources();
    resources.getDisplayMetrics().xdpi = size.x / designWidth * 72f;
    DisplayMetrics metrics = getMetricsOnMIUI(context.getResources());
    if (metrics != null)
        metrics.xdpi = size.x / designWidth * 72f;
}
/**
 * 解决MIUI屏幕适配问题
 *
 * @param resources
 * @return
 */
private static DisplayMetrics getMetricsOnMIUI(Resources resources) {
    if ("MiuiResources".equals(resources.getClass().getSimpleName()) || "XResources".equals(resources.getClass().getSimpleName())) {
        try {
            Field field = Resources.class.getDeclaredField("mTmpMetrics");
            field.setAccessible(true);
            return (DisplayMetrics) field.get(resources);
        } catch (Exception e) {
            return null;
        }
    }
    return null;
}

猜你喜欢

转载自blog.csdn.net/freak_csh/article/details/85165554