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"
/>
并盡可能多地使用:重力等字段而不是常數。
添加回答
舉報
