android textview全角,bug-textview半角,英文展示不全

在android的原生TextView中遇到如图所示等情况,由于特殊符号半角、或者字母串等等,TextView自动分割机制作出的效果并不美观。

abd5343bc583?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

abd5343bc583?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

尝试方案:

添加半角转全角后—一个数字或字母占两个字符,看似一行占满,但是间隙变大,视觉效果差。如下图

abd5343bc583?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

abd5343bc583?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

最终解决方案:

获取每一个字符测量长度,手动添加换行符。重新设置text。

public class AutoSplitTextView extends TextView {

private String autoText;

private float textWidth;

private float textHeight;

private Paint textPaint;

public AutoSplitTextView(Context context) {

this(context,null);

}

public AutoSplitTextView(Context context, @Nullable AttributeSet attrs) {

this(context, attrs,0);

}

public AutoSplitTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {

super(context, attrs, defStyleAttr);

}

//解决首次渲染,没有补全的bug。

int mWidth = -1;

@Override

protected void onDraw(Canvas canvas) {

//onDraw可能会被多次调用,因此不是每次调用都需要重绘,这里做了个判断,text是否跟上一次一样,若一样,不再计算,否则重新计算赋值

if(mWidth != getWidth() || !autoText.equals(getText().toString()) ){

autoText=autoSplitText(this);

setText(autoText);

mWidth = getWidth();

}

super.onDraw(canvas);

}

private String autoSplitText(AutoSplitTextView textView) {

CharSequence rawCharSequence = textView.getText();

String originText = rawCharSequence.toString();//获取原始文本

textPaint = textView.getPaint();

textWidth = textView.getWidth() - textView.getPaddingLeft() - textView.getPaddingRight();

textHeight = textView.getHeight();

String allTextLines=originText.replaceAll("\n","");

StringBuilder stringBuilder = new StringBuilder();

if (textPaint.measureText(allTextLines)>textWidth){

//如果整行宽度超过控件所用宽度,则按字符测量,在超过可用宽度的最后一个字符添加换行符

float lineWidth = 0;

for (int i = 0; i < allTextLines.length(); i++) {

char textChar = allTextLines.charAt(i);

lineWidth += textPaint.measureText(String.valueOf(textChar));

if (lineWidth <= textWidth) {

stringBuilder.append(textChar);

} else {

stringBuilder.append("\n");

i--;

lineWidth = 0;

}

}

}else {

stringBuilder.append(allTextLines);

}

return stringBuilder.toString();

}

}

然后我们再来看一下

abd5343bc583?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

abd5343bc583?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation

image.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值