zoukankan      html  css  js  c++  java
  • Android中 TextView 加载 混合字符 自动换行解决方案

    昨天测试提看一个bug,如下:

    【3.1.0】当实勘员点评由中文和数字组成时,第一个中文后会自动换行 

    最终解决办法为加入这个方法:

     private String autoSplitText(final TextView tv) {
            final String rawText = tv.getText().toString(); //原始文本
            final Paint tvPaint = tv.getPaint(); //paint,包含字体等信息
            final float tvWidth = tv.getWidth() - tv.getPaddingLeft() - tv.getPaddingRight(); //控件可用宽度
    
            //将原始文本按行拆分
            String[] rawTextLines = rawText.replaceAll("
    ", "").split("
    ");
            StringBuilder sbNewText = new StringBuilder();
            for (String rawTextLine : rawTextLines) {
                if (tvPaint.measureText(rawTextLine) <= tvWidth) {
                    //如果整行宽度在控件可用宽度之内,就不处理了
                    sbNewText.append(rawTextLine);
                } else {
                    //如果整行宽度超过控件可用宽度,则按字符测量,在超过可用宽度的前一个字符处手动换行
                    float lineWidth = 0;
                    for (int cnt = 0; cnt != rawTextLine.length(); ++cnt) {
                        char ch = rawTextLine.charAt(cnt);
                        lineWidth += tvPaint.measureText(String.valueOf(ch));
                        if (lineWidth <= tvWidth) {
                            sbNewText.append(ch);
                        } else {
                            sbNewText.append("
    ");
                            lineWidth = 0;
                            --cnt;
                        }
                    }
                }
                sbNewText.append("
    ");
            }
    
            //把结尾多余的
    去掉
            if (!rawText.endsWith("
    ")) {
                sbNewText.deleteCharAt(sbNewText.length() - 1);
            }
    
            return sbNewText.toString();
        }
    View Code

    加载完调用:

       tvDes.setText(desc.getSurvey_conclusion());
            tvDes.setText(autoSplitText(tvDes));
    View Code

    如果出现不正常的问题,再换种方式调用,:

       ViewTreeObserver observer = tvDes.getViewTreeObserver();
            observer.addOnGlobalLayoutListener(
                    new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            tvDes.setText(autoSplitText(tvDes));
                        }
                    });
    View Code

    就可以了。

  • 相关阅读:
    javascript时间戳和日期字符串相互转换
    jquery两稳定版本比较~~
    原生的强大DOM选择器querySelector
    分享一个自定义的 console 类,让你不再纠结JS中的调试代码的兼容
    基于Mesos运行Spark
    chrome插件 postman 可以调用restful服务
    cassandra优秀博客集
    Cassandra监控
    Cassandra
    SecureCRT中文显示乱码的解决方法
  • 原文地址:https://www.cnblogs.com/itpepe/p/5732685.html
Copyright © 2011-2022 走看看