Hi @Daniel if u programmatically generate textview as following code
TextView tv = new TextView();
tv.setTextSize(10); // Sets text in sp (Scaled Pixel).
And if you want to set text size with other unit so you can achieved by following way.
TextView tv = new TextView();
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, 10); // Sets text in px (Pixel).
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10); // Sets text in dip (Device Independent Pixels).
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10); // Sets text in sp (Scaled Pixel).
tv.setTextSize(TypedValue.COMPLEX_UNIT_PT, 10); // Sets text in pt (Points).
tv.setTextSize(TypedValue.COMPLEX_UNIT_IN, 10); // Sets text in in (inches).
tv.setTextSize(TypedValue.COMPLEX_UNIT_MM, 10); // Sets text in mm (millimeters).
By default Android uses "sp" for text size and "px" for view size.
For other View sizes we can set in px(pixels) but if you want customize the unit you can use custom methods
/**
* Converts dip to px.
*
* @param context - Context of calling class.
* @param dip - Value in dip to convert.
* @return - Converted px value.
*/
public static int convertDipToPixels(Context context, int dip) {
if (context == null)
return 0;
Resources resources = context.getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, resources.getDisplayMetrics());
return (int) px;
}
From above method you can convert YOUR_DESIRED_UNIT in pixels and then set to view. You can replace
TypedValue.COMPLEX_UNIT_DIP
with above unit as per you use case. You can also use it vice-versa for px to dip but we cant assign to custom unit to view so that's why i am using it like this.
I hope i explained well this.