How to adjust the view so they are small independent of the device?

0

I made an application where I create part of the interface in xml and part via java code, the part in xml works in any application adapting the screen size correctly. The part via code on a 7.8-inch device looks good, however on a 4-inch screen it's all unconfigured (source of the giant views). I've done a lot of research on the internet and nothing works. Anyone know what I can do? Thank you in advance.

I tried to use this code but it did not work:

tv2.setTextSize(20 * getResources().getDisplayMetrics().scaledDensity);
    
asked by anonymous 11.01.2016 / 17:25

1 answer

1

If the problem is only the size of the fonts, you can use the following to solve your problem.

You must first determine which device is running your application.

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    int widthPixels = metrics.widthPixels;
    int heightPixels = metrics.heightPixels;

    float scaleFactor = metrics.density;

    float widthDp = widthPixels / scaleFactor;
    float heightDp = heightPixels / scaleFactor;

    float smallestWidth = Math.min(widthDp, heightDp);

After discovering the value of smallestWidth you can determine whether you are running the application on a 7, 10-inch tablet or a smartphone and adjust the text size accordingly.

// tamanho para smartphone
int size = 10

if (smallestWidth > 720) {
    //tablet de 10"
    size = 20

} else if (smallestWidth > 600) {
    //tablet de 7"
    size = 15
}

After determining the size you can configure your view.

tv2.setTextSize(size)

I hope I have helped.

Adapted response from here .

    
12.01.2016 / 20:19