Use DIP, SP metrics programmatically
Today I had this problem where I needed to create some TextViews inside a TableRow, but I needed to specify its setMinWidth with some value in the SP metrics, like you do at the XML file: setWidth=”100sp”. The problem is that setMinWidth or setWidth are called giving a number in pixels. So I searched a little bit and found this simple solution.
The goal is to calculate the number of pixels according to a given value in the SP metrics. Converting 20sp into pixels is done by doing
TextView tv0 = new TextView(this); int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics()); tv0.setMinimumWidth(px);
And that’s it!
If you want it with the DIP metrics, you just need to change the TypedValue from TypedValue.COMPLEX_UNIT_SP to TypedValue.COMPLEX_UNIT_DIP or whatever other metric you want to use.
Hope it was helpful.