TextView,很常見的控件。關於文字大小的方法有:
android.widget.TextView#getTextSize 返回值的單位是PX
/**
* @return the size (in pixels) of the default text size in this TextView.
*/
@ViewDebug.ExportedProperty(category = "text")
public float getTextSize() {
return mTextPaint.getTextSize();
}
android.widget.TextView#getScaledTextSize 返回值單位是SP
/**
* @return the size (in scaled pixels) of thee default text size in this TextView.
* @hide
*/
@ViewDebug.ExportedProperty(category = "text")
public float getScaledTextSize() {
return mTextPaint.getTextSize() / mTextPaint.density;
}
android.widget.TextView#setTextSize(float) 參數的單位是SP
/**
* Set the default text size to the given value, interpreted as "scaled
* pixel" units. This size is adjusted based on the current density and
* user font size preference.
*
* @param size The scaled pixel size.
*
* @attr ref android.R.styleable#TextView_textSize
*/
@android.view.RemotableViewMethod
public void setTextSize(float size) {
setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
}
android.widget.TextView#setTextSize(int, float) 參數的單位是兩個,第一個是單位,第二個是數值
/**
* Set the default text size to a given unit and value. See {@link
* TypedValue} for the possible dimension units.
*
* @param unit The desired dimension unit.
* @param size The desired size in the given units.
*
* @attr ref android.R.styleable#TextView_textSize
*/
public void setTextSize(int unit, float size) {
Context c = getContext();
Resources r;
if (c == null)
r = Resources.getSystem();
else
r = c.getResources();
setRawTextSize(TypedValue.applyDimension(
unit, size, r.getDisplayMetrics()));
}
總結:
- get方法,注意返回值的單位
- set方法,注意參數的單位
補充
在自定義控件中使用自定義屬性時,經常需要使用java代碼獲取在xml中定義的尺寸,相關有以下三個函數
- getDimension()
- getDimensionPixelOffset()
- getDimensionPixelSize()
它們三個返回值的單位都是:PX
