简体   繁体   中英

Android - setting layout params to TextView in millimeter

I believe you can set layout_width and layout_height to textview element dynamically using something like:

LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
centimeterLayout.addView(textview, lparams);

But - how do I set the layout width and height in other units - eg I want to set the layout width of my text view to 20 mm. How do I do that?

LayoutParams either take one of the constants ( FILL_PARENT , WRAP_CONTENT ) or a pixel value. Since you want to use millimeters, you have to convert a millimeter dimension to a pixel dimension. Doing so is pretty easy:

Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_MM, 20, 
                                     r.getDisplayMetrics());

In this example, 20 mm are converted into a pixel dimension that you can use in your LayoutParams . You can use other dimensions too, such as TypedValue.COMPLEX_UNIT_DIP for dp/dip¹. Just change the constant in the arguments. The android doc has a list of useable dimensions .

¹ Density independend pixels, a highly recommended dimension that adjusts to the many different screen sizes and densities. Using mm isn't the best way to do things, since your text will probably look okay on a big screen and fill a big portion of a small screen, or the other way around - which is not ideal. I also recommend sp for font sizes. See the dimension list for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM