Auto - generate custom dimen for Android using kotlin

What are dimensions?

If you’re not sure what a dimensions value is, it’s an XML value that lives in your project’s res/values folder, under dimens.xml. They’re intended to be used for styling dimensions (hence the name) such as width, height, etc.

Dimensions for Re-usability

The simplest reason to use a dimension value is when you know that value needs to be reused. If you were to change this value in one place, you would want to change it elsewhere — which is a perfect case for a dimension value.

Dimensions for Screen Density

Given how popular ConstraintLayout is, it’s sometimes easy to forget that screen density is even a thing. However, like all resource files, you can build a dimens.xml for different screen densities or other device properties (such as Locale). Perhaps you want different measurements on high density devices or you may even want to remove extra margins on small density devices. The dimens.xml file can be qualified to a screen density to allow customization on different devices.

Without wasting much of your time, lets get to the practical business of the day.

STEP 1.

Create a new project on android studio or open your already existing project.

STEP 2.

create a new tools folder in your project directory, so you don’t mix it with your project files. create a new class in the tools folder, copy the below code and paste inside, import all files if not auto imported.

STEP 3.

run the file by clicking on the green forward arrow, select Run ‘GenerateDimenTool’ and wait for the execution to end, and then you will see the generated dimens.xml file in the corresponding directory.

you can adjust the number of dimen to suit your project in the for loop. Below is an example of used case:

That is it, no more stress of having to create your dimen manually. Happy coding. Please feel free to leave a comment. Thanks.

https://github.com/sunday58/CustomDimen

Android Software Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store