版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/q1269463/article/details/63258782
现在项目遇到了一个需求文字能够自动换行,本来想通过当前view的宽度和字体大小进行处理。在查阅资料后,发现android本身就提供了这方面的功能。StaticLayout能够让文字进行自动行,直接上代码:
public class StaticLayoutText extends View{
private TextPaint mTextPaint;
private StaticLayout mStaticLayout;
private String str = “职场人士,白天忙着上班,大部分的人生活极其相似。” +
“他们或者疲于追逐业绩,或者忙着大会小会,或者奔跑于迎合他人。” +
“职场普通人,难有掌握白天生活的权利,他们依附于公司、或屈从于领导,” +
“但有层次的人,其晚上生活丰富多彩。” +
“有的职场人士,上班后一头窝在沙发里,舒舒服服等待天明;” +
“有的则一心放在电视剧或综艺,满脸的痴迷像;” +
“有的则不停聊着微信刷着朋友圈,生怕静下来觉得自己落寞。” +
“这些生活的样式暂不论好坏,终不算有层次的生活。”;
public StaticLayoutText(Context context) {
this(context,null);
}
public StaticLayoutText(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public StaticLayoutText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init(){
mTextPaint = new TextPaint();
mTextPaint.setTextSize(40);
mTextPaint.setColor(Color.BLACK);
mTextPaint.setAntiAlias(true);
mTextPaint.setTextAlign(Paint.Align.LEFT);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mStaticLayout = new StaticLayout(str,mTextPaint,getWidth(),
Layout.Alignment.ALIGN_NORMAL,1f,0f,false);
mStaticLayout.draw(canvas);
}
}
执行代码的结果: