当前位置:   article > 正文

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

android textview 英文yg 显示不全

在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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/242953
推荐阅读
相关标签
  

闽ICP备14008679号