在 axml 文件中添加视图时,可以简单地指定视图属性的大小和单位,例如:
<TextView
android:TextSize = "10sp"
android:layout_marginTop = "10dp" />
如本回答所述,有用于特定目的的特定单元。
我的主要问题是,当以编程方式(通过代码(动态应用大小时,为大小应用的单位是什么?
例如,当声明像这样的 TextSize 时:
TextView tv = new TextView();
tv.TextSize = 10;
文本大小的单位是什么? sp? dp? px?
最重要的是,我如何更改它们以满足我的需求?
嗨@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 下降,但我们不能分配给自定义单位进行查看,这就是我这样使用它的原因。
我希望我解释得很好。
首先:
我认为您应该尽可能避免以编程方式设置大小。
第二:
像素像素 :对应于屏幕上的实际像素。
DP 或 DIP与密度无关的像素 - :基于屏幕物理密度的抽象单位。这些单位相对于 160 dpi 屏幕,因此 1 dp 是 160 dpi 屏幕上的一个像素
sp与比例无关的像素 - :这类似于 dp 单元,但它也由用户的字体大小偏好缩放
在你的第三个问题中,我认为:
例如:
对于编辑文本,您不应该像这样对宽度使用常量:
<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"
/>
并尽可能多地使用字段,例如:重力和其他而不是常数。