Android Question Need your help:low-cost Android screen adaptation method


Active Member
Licensed User
Longtime User
I find a very low-cost Android screen adaptation method which is used on some mainstream App. The code is written in Java,I'm not familiar with JAVA at all. I use B4A inline java code, but the debugging fails. Can anyone help solve this problem, I think this method is of great benefit to Android adaptation.You can see Attach file.

Java Code:
#if JAVA

import android.os.Bundle;
import android.content.ComponentCallbacks;
import android.content.res.Configuration;
import android.util.DisplayMetrics;

public class LayoutAdaption {

     // System Density
     private static float sNoncompatDensity;
     // System ScaledDensity
     private static float sNoncompatScaledDensity;

     public static void setCustomDensity(@NonNull AppCompatActivity activity, @NonNull final Application application) {
            DisplayMetrics displayMetrics = application.getResources().getDisplayMetrics();
            if (0 == sNonCompatDensity) {
                sNoncompatDensity = Metrics.density;
                sNoncompatScaledDensity = Metrics.scaledDensity;
                // Listen to switch fonts in system settings
                application.registerComponentCallbacks(new ComponentCallbacks() {
                    public void onConfigurationChanged(Configuration newConfig) {
                        if (null != newConfig && newConfig.fontScale > 0) {

                    public void onLowMemory() {

            // Here is a 360dp design as an example
            final float targetDensity=Metrics.widthPixels/360;
            final float targetScaledDensity=targetDensity*(sNoncompatScaledDensity/sNoncompatDensity);
            final int targetDensityDpi= (int) (160 * targetDensity);
            Metrics.density = targetDensity;
            Metrics.scaledDensity = targetScaledDensity;
            Metrics.densityDpi = targetDensityDpi;

            DisplayMetrics activityDisplayMetrics = activity.getResources().getDisplayMetrics();
            activityMetrics.density = targetDensity;
            activityMetrics.scaledDensity = targetScaledDensity;
            activityMetrics.densityDpi = targetDensityDpi;

#end if

A more advanced method, hope someone wraps it for B4A.


    91.4 KB · Views: 146
Last edited: