今天,简单讲讲android的TextView 的setTextSize方法的使用。
之前,我看代码时发现了这个函数,于是在网上查询了这个函数的用法,发现之前自己了解的不够全面,所以这里记录一下。
看了看TextView的源码:
public void setTextSize(float size) {
setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
}
我们平时使用setTextSize()的时候都是只用了一个参数,那TypedValue.COMPLEX_UNIT_SP又是个什么鬼?别急来看看下面的代码:
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()));
}
这是我们在使用setTextView()的时候系统去帮我们做的事,第一个参数是系统默认使用的单位,第二个就是我们设置的文字大小值。那么TypedValue.COMPLEX_UNIT_SP到底是什么呢?
public static final int COMPLEX_UNIT_PX = 0;
/** {@link #TYPE_DIMENSION} complex unit: Value is Device Independent
* Pixels. */
public static final int COMPLEX_UNIT_DIP = 1;
/** {@link #TYPE_DIMENSION} complex unit: Value is a scaled pixel. */
public static final int COMPLEX_UNIT_SP = 2;
不难看出0是代表px,1是dp,2是sp也就是系统默认使用的单位。
至此也就清楚了在代码里面使用setTextView()时,文字的单位也是用的sp。
setTextSize(int unit, int size) 参数的具体意义:
第一个参数可设置如下静态变量:
TypedValue.COMPLEX_UNIT_PX : Pixels
TypedValue.COMPLEX_UNIT_SP : Scaled Pixels
TypedValue.COMPLEX_UNIT_DIP : Device Independent Pixels
下面举一些具体的应用:
1.产品中有一个需求是根据TextVIew显示的内容的大小设置字体大小:
// 优惠券金额为三位数时,更改字体大小if (couponAmunt.length() >= 3) {
holder.favourItemPriceUnit.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
holder.favourItemPrice.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 30);
} else {
holder.favourItemPrice.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 36);
holder.favourItemPriceUnit.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);}
2.根据textview长度自动调节文字大小
tv是需要自动调节文字大小的Textview
Paint testPaint = tv.getPaint();
String text = tv.getText().toString();
int textWidth = tv.getMeasureWidth();
if (textWidth > 0) {
int availableWidth = textWidth - tv.getPaddingLeft() -
tv.getPaddingRight();
float trySize = tv.getTextSize();
testPaint.setTextSize(trySize);
while ((testPaint.measureText(text) > availableWidth)) {
trySize -= 2;
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, trySize); //这里必须使用px,因为testPaint.measureText(text)和availableWidth的单位都是px
}
tv.setTextSize(trySize);
}
android TextView 的setTextSize方法的使用就讲完了。
就这么简单。