2 回答
TA贡献1853条经验 获得超6个赞
如果你以编程方式生成文本视图如下代码
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 下降,但我们不能分配给自定义单位来查看,所以这就是我这样使用它的原因。
我希望我解释得很好。
TA贡献1744条经验 获得超4个赞
第一的:
我认为您应该尽可能避免以编程方式设置大小。
第二:
px Pixels :对应于屏幕上的实际像素。
dp 或 dip 与密度无关的像素-:基于屏幕物理密度的抽象单位。这些单位是相对于 160 dpi 屏幕的,因此 1 dp 是 160 dpi 屏幕上的一个像素
sp Scale-independent Pixels- :这类似于 dp 单位,但它也根据用户的字体大小偏好进行缩放
在你的第三个问题中,我认为:
例如 :
对于edittext,您不应该像这样对宽度使用常量:
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="@string/banklist_firstselectbank"
style="@style/TextAppearanceHeadline2"
android:gravity="center"/>
我认为最好像这样使用边距开始和边距结束:
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="@string/banklist_firstselectbank"
style="@style/TextAppearanceHeadline2"
android:layout_marginEnd="50dp"
android:layout_marginStart="50dp"
android:gravity="center"
/>
并尽可能多地使用:重力等字段而不是常数。
添加回答
举报
