TextView textSize 文字大小

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





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值