Generation of Android dimensions density adaptation file

Time:2021-5-11

When writing XML, we directly specify a fixed width and height of a control, and give a fixed DP value. The display on different screens is very different. As a result, the layout of some mobile phones can not be displayed normally, so we need to adapt the screen. The adaptation methods here are the same, but the methods are different

First of all, the old adaptation is to calculate by yourself and then generate a file. I have done this before. I directly specify the size I need, then calculate and generate the code, and then copy it to the project for use. The commonly used sizes are as follows

 

The execution code will generate the corresponding dimensions. XML class according to the defined size. Here is the code

Generation of Android dimensions density adaptation fileGeneration of Android dimensions density adaptation file

package com.example.myapplication;

import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;

public class MakeUtils {

    private static final String XML_HEADER = "\r\n";
    private static final String XML_RESOURCE_START = "\r\n";
    private static final String XML_RESOURCE_END = "\r\n";
    private static final String XML_DIMEN_TEMPLETE = "%3$.2fdp\r\n";

    private static final String XML_BASE_DPI = "%ddp\r\n";
    private  static final int MAX_SIZE = 720;

    private static final String XML_NAME = "dimens.xml";

    public static float px2dip(float pxValue, int sw,int designWidth) {
        float dpValue =   (pxValue/(float)designWidth) * sw;
        BigDecimal bigDecimal = new BigDecimal(dpValue);
        float dp = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        return dp;
    }

    /**
     *Generate all dimension data
     */
    private static String createDimens(DimenTypes type, int designWidth) {
        float dpValue;
        String temp;
        StringBuilder sb = new StringBuilder();
        try {
            sb.append(XML_HEADER);
            sb.append(XML_RESOURCE_START);
            //Information about backup generation
            temp = String.format(XML_BASE_DPI, type.getSwWidthDp());
            sb.append(temp);
            for (int i = 0; i <= MAX_SIZE; i++) {

                dpValue = px2dip((float) i,type.getSwWidthDp(),designWidth);
                temp = String.format(XML_DIMEN_TEMPLETE,"", i, dpValue);
                sb.append(temp);
            }
            sb.append(XML_RESOURCE_END);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     *Generated destination folder
     */
    public static void create(int designWidth, DimenTypes type, String buildDir) {
        try {
            //Generation rules
            final String folderName;
            if (type.getSwWidthDp() > 0) {
                //Adapt to Android 3.2+
                folderName = "values-sw" + type.getSwWidthDp() + "dp";
            }else {
                return;
            }

            //Generate target directory
            File file = new File(buildDir + File.separator + folderName);
            if (!file.exists()) {
                file.mkdirs();
            }
            Log.e("===",file.getAbsolutePath());
            //Generate values file
            FileOutputStream fos = new FileOutputStream(file.getAbsolutePath() + File.separator + XML_NAME);
            fos.write(createDimens(type,designWidth).getBytes());
            fos.flush();
            fos.close();


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

View Code

Generation of Android dimensions density adaptation fileGeneration of Android dimensions density adaptation file

package com.example.myapplication;

/**
 * created by YooJin.
 * date: 2021/2/3 13:50
 * ldpi: 120  density:1dp=0.75px  Representative size 240 * 320
 * mdpi: 160  density:1dp=1px  Representative size 320 * 480
 * hdpi: 240  density:1dp=1.5px  Representative size 480 * 800
 * xhdpi: 320  density:1dp=2px  Representative size 720 * 1280
 * xxhdpi: 480  density:1dp=3px  Representative size 1080 * 1920
 */
enum DimenTypes {

    DP_sw__160(160),
    DP_sw__240(240),
    DP_sw__280(280),
    DP_sw__320(320),  
    DP_sw__360(360),
    DP_sw__400(400),
    DP_sw__420(420),
    DP_sw__440(440),
    DP_sw__480(480),
    DP_sw__560(560),
    DP_sw__640(640),
    DP_sw__720(720),
    DP_sw__800(800);

    /**
     *Minimum screen width
     */
    private int swWidthDp;

    DimenTypes(int swWidthDp) {

        this.swWidthDp = swWidthDp;
    }

    public int getSwWidthDp() {
        return swWidthDp;
    }

    public void setSwWidthDp(int swWidthDp) {
        this.swWidthDp = swWidthDp;
    }

}

View Code

Generation of Android dimensions density adaptation fileGeneration of Android dimensions density adaptation file

package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    /**
     *Design draft size, from zero, the maximum size generated
     */
    private static final int DESIGN_WIDTH = 375;

    String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    List mPermissionList = new ArrayList<>();

    private static final int PERMISSION_REQUEST = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        checkPermission();
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + "res";
        TextView tvTag = findViewById(R.id.tv_tag);
        tvTag.setText(path);
        DimenTypes[] values = DimenTypes.values();
        for (DimenTypes value : values) {
            MakeUtils.create(DESIGN_WIDTH, value, path);
        }
    }

    private void checkPermission() {
        mPermissionList.clear();

        //Determine which permissions are not granted
        for (int i = 0; i < permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissions[i]);
            }
        }
        /**
         *Judge whether it is empty
         */
        If (mpermissionlist. Isempty()) {// the permissions that are not granted are empty, indicating that they are granted

        }Else {// request permission method
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);// Convert list to array
            ActivityCompat.requestPermissions(MainActivity.this, permissions, PERMISSION_REQUEST);
        }
    }

    /**
     *Response authorization
     *Here, no matter whether the user refuses or not, they will enter the home page and no longer apply for permission repeatedly
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case PERMISSION_REQUEST:

                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }

}

View Code

Print out the path after executing the code. Here is the res file in the download directory. Note that you need to apply for permission first, and then cut out the generated file

The dimensions file is generated in it

 

Directly copy the file to the project and you can use it directly. Is there any convenient switch

Android studio has a plug-in on it   Screenmatch can generate these files directly after installation, and can be configured dynamically, which is very convenient

After installation, right-click to have a screen match menu and click it

Then you will find that you already have two configuration files in your project

A dimensions.xml file is an example. To generate the base class of the file, you need to copy the values in it to the dimensions.xml file under your own values. If you don’t have this file in your project, create it manually

The other is the generated configuration file, which configures some sizes you need to generate. By default, it has some sizes. You can add those you don’t need and filter those you don’t need

Then right click to select   Screenmatch, the size XML file in the configuration will appear in the project

Compare with the old value to verify whether it is correct. At the same time, open the XML in sw240dp to correspond to the value in it

  

The one on the left is generated by the code, and the one on the right is generated by the plug-in, DP1 = 0.64, DP2 = 1.28. Then let’s open the XML in sw800dp

  

DP1 = 2.13, DP2 = 4.27, indicating that the two methods are the same, but there are plug-ins to save our calculation

github:https://github.com/1024477951/KotlinStrong

Recommended Today

Analysis on the investigation scheme of the integrated platform of medical and welfare (2)

Business Tags: hospital information integration platform, Internet hospital, Internet nursing, chronic disease follow-up Technical labels: ESB, ETL + CDC, NLP, FAAS, SaaS, Hadoop, microservice   Technology wechat group:Add wechat: wonter send: technical QMedical wechat group:Add wechat: wonter send: Medical Q   —————— BEGIN ——————   Analysis on the investigation scheme of Neusoft integration platform (1) […]