嗨@Daniel,如果你以编程方式生成如下代码的文本视图
TextView tv = new TextView();
tv.setTextSize(10); // Sets text in sp (Scaled Pixel).
如果你想用其他单位设置文本大小,那么你可以通过以下方式实现。
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).
默认情况下,Android 使用“sp”作为文本大小,使用“px”作为视图大小。
对于其他视图尺寸,我们可以设置为 px(像素),但如果您想自定义单位,您可以使用自定义方法
/**
* 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;
}
通过上述方法,您可以将 YOUR_DESIRED_UNIT 转换为像素,然后设置为视图。你可以替换
TypedValue.COMPLEX_UNIT_DIP
根据您的用例使用上述单位。您也可以反之亦然,让 px 下降,但我们不能分配给自定义单位来查看,所以这就是我这样使用它的原因。
我希望我解释得很好。