开发者

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 oth开发者_开发问答er units - e.g. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜