Android 自定义设置文本字体间间距
程序员文章站
2022-04-28 13:09:45
自定义spacingtextview 继承textview,代码如下:
public class spacingtextview extends textview {
private float l...
自定义spacingtextview 继承textview,代码如下:
public class spacingtextview extends textview {
private float letterspacing = letterspacing.biggest;
private charsequence originaltext = “”;
public spacingtextview(context context) { super(context); } public spacingtextview(context context, attributeset attrs){ super(context, attrs); originaltext = super.gettext(); applyletterspacing(); this.invalidate(); } public spacingtextview(context context, attributeset attrs, int defstyle){ super(context, attrs, defstyle); } public float getletterspacing() { return letterspacing; } public void setletterspacing(float letterspacing) { this.letterspacing = letterspacing; applyletterspacing(); } @override public void settext(charsequence text, buffertype type) { originaltext = text; applyletterspacing(); } @override public charsequence gettext() { return originaltext; } /** * 字距为任何字符串(技术上,一个简单的方法为charsequence不使用)的textview */ private void applyletterspacing() { if (this == null || this.originaltext == null) return; stringbuilder builder = new stringbuilder(); for(int i = 0; i < originaltext.length(); i++) { string c = ""+ originaltext.charat(i); builder.append(c.tolowercase()); if(i+1 < originaltext.length()) { builder.append("\u00a0"); } } spannablestring finaltext = new spannablestring(builder.tostring()); if(builder.tostring().length() > 1) { for(int i = 1; i < builder.tostring().length(); i+=2) { finaltext.setspan(new scalexspan((letterspacing+1)/10), i, i+1, spannable.span_exclusive_exclusive); } } super.settext(finaltext, buffertype.spannable); } public class letterspacing { public final static float normal = 0; public final static float normalbig = (float)0.025; public final static float big = (float)0.05; public final static float biggest = (float)0.2; }
}
代码中调用:
public class spacingtextviewactivity extends baseactivity {
private spacingtextview spacingtextview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_spacing_text_view); spacingtextview=findview(r.id.space_text); spacingtextview.settext(getresources().getstring(r.string.space_test)); spacingtextview.setletterspacing(convertutils.dip2px(this,20)); }
}