热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Android开发之TextView排版问题

下面直接是关于解决该问题的代码(根据别人的代码进行了修正以及测试,保证可以修改字体尺寸、颜色、根据padding调整,如果需要支持其他的格式可以将对应的属性添加至Paint类型的对象中):

下面直接是关于解决该问题的代码(根据别人的代码进行了修正以及测试,保证可以修改字体尺寸、颜色、根据padding调整,如果需要支持其他的格式可以将对应的属性添加至Paint类型的对象中):

 1 public class NsTextView extends TextView {
 2     private String text;
 3     private float textSize;
 4     private float paddingLeft;
 5     private float paddingRight;
 6     private int textColor;
 7     private Paint paint1 = new Paint();
 8     private float textShowWidth;
 9 
10     public NsTextView(Context context, AttributeSet attrs) {
11         super(context, attrs);
12         text = this.getText().toString();
13         textSize = this.getTextSize();
14         textColor = this.getTextColors().getDefaultColor();
15         paddingLeft = this.getPaddingLeft();
16         paddingRight = this.getPaddingRight();
17         paint1.setTextSize(textSize);
18         paint1.setColor(textColor);
19         paint1.setAntiAlias(true);
20     }
21 
22     @Override
23     protected void onDraw(Canvas canvas) {
24         textShowWidth = this.getMeasuredWidth() - paddingLeft - paddingRight;
25         int lineCount = 0;
26         text = this.getText().toString();
27         if (text == null)
28             return;
29         char[] textCharArray = text.toCharArray();
30         float drawedWidth = 0;
31         float charWidth;
32         for (int i = 0; i ) {
33             charWidth = paint1.measureText(textCharArray, i, 1);
34             if (textCharArray[i] == '\n') {
35                 lineCount++;
36                 drawedWidth = 0;
37                 continue;
38             }
39             if (textShowWidth - drawedWidth < charWidth) {
40                 lineCount++;
41                 drawedWidth = 0;
42             }
43             canvas.drawText(textCharArray, i, 1, paddingLeft + drawedWidth,
44                     (lineCount + 1) * textSize, paint1);
45             drawedWidth += charWidth;
46         }
47         setHeight((int) ((lineCount + 1) * (int) textSize ));
48     }
49 }

 


推荐阅读
author-avatar
素子花开365
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有