问题描述:

I have a TableLayout on my app where I am adding rows programatically by getting data from the local SQLite DB. Since I also create the TextViews on each row programatically I need to specify one text size for them, and that size won't be suitable for all screen sizes. If I pick one that looks good on a smartphone, for instance, it will look too small on large tablets.

If I had the TextViews on the XML I could simply create a different layout for each screen size, but how can I achieve that flexibility in text size creating the TextViews programatically?

Thanks a lot in advance.

网友答案:

I ended up solving it with the approach below. Not the most elegant, but worked pretty well:

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
double x = Math.pow(dm.widthPixels/dm.xdpi,2);
double y = Math.pow(dm.heightPixels/dm.ydpi,2);
double screenInches = Math.sqrt(x+y);

int textsize = 0;

if(screenInches<5)
        textsize = 16;
else if(screenInches<7.5)
        textsize = 22;
else
        textsize = 24;  
相关阅读:
Top