android TextView 的setTextSize方法的使用_暴走邻家的博客-CSDN博客

看了看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。 简单讲讲,使用TextView .setTextSize()时,字体的默认单位是sp,也可以自己修改单位,如 setTextSize(TypedValue.COMPLEX_UNIT_DIP, size)这里的单位就是dp了。 setTextSize(int unit, int size) 参数的具体意义: 第一个参数可设置如下静态变量: TypedValue.COMPLEX_UNIT_PX : Pixels TypedValue.COMPLEX_UNIT_SP : Scaled Pixels TypedValue.COMPLEX_UNIT_DIP : Device Independent Pixels 关键代码 - setTextSize(TypedValue.COMPLEX_UNIT_PX,15); //22像素 - setTextSize(TypedValue.COMPLEX_UNIT_SP,15); //22SP - setTextSize(TypedValue.COMPLEX_UNIT_DIP,15);//22DIP 下面举一些具体的应用: 1.产品中有一个需求是根据TextVIew显示的内容的大小设置字体大小: 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); }
你可能想看的