How do I adjust the views to make them small independent of the device?

Asked

Viewed 40 times

0

I made an application where I create part of the interface in xml and part via java code, the xml part works in any application adapting the screen size. The part via code in a 7.8 inch device is good, but in a 4 inch screen is all disfigured (source of the giant views). I’ve researched a lot on the Internet and nothing works. Does anyone know what I can do? Thanks in advance.

I tried to use this code but it didn’t work:

tv2.setTextSize(20 * getResources().getDisplayMetrics().scaledDensity);
  • This code you posted can cause this problem. If you are always using tv2.setTextSize(20); then the problem is elsewhere. Place the code where you create these views.

  • i only use Textview in this application, if I put setTextSize(x) also of the problem.

1 answer

1


If the problem is just the font size, you can use the following to solve your problem.

First you must determine on which device your application is running.

    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 tablet of 7, 10 inches or on 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’ve helped.

Adapted response from here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.