0%

获取textview行数

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import android.content.Context;
import android.graphics.Canvas;
import android.text.Layout;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;
/**
* @author jasonkent27
*
* TextView第二行文字超过一半则自动略去,并添加省略号
*/
public class CustomWidgetTextView extends TextView {
private float mLineSpacingMultiplier = 1.0f;
private float mLineAdditionalVerticalPadding = 0.0f;
/**
* setText时需要置为true
*/
private boolean mNeedResetText = true ;
public CustomWidgetTextView(Context context) {
this(context, null);
}
public CustomWidgetTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomWidgetTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected final void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
mNeedResetText = true ;
}
@Override
protected void onDraw(Canvas canvas) {
if (mNeedResetText) {
resetText();
mNeedResetText = false ;
}
super.onDraw(canvas);
}
/**
* 重TextView内部文字渲染逻辑
*/
private void resetText() {
if (!TextUtils.isEmpty(getText())) {
String origText = getText().toString();
String firstLineText ;
String secondLineText ;
String resultText = origText ;
Layout layout = createRenderLayout(origText, getWidth() - getPaddingLeft() - getPaddingRight());
if (layout.getLineCount() > 1) {
//取出第一,二行文字
firstLineText = origText.substring(0, layout.getLineEnd(0));
secondLineText = origText.substring(layout.getLineEnd(0)+1, layout.getLineEnd(1));
Layout layout2 = createRenderLayout(secondLineText, (getWidth() - getPaddingLeft() - getPaddingRight()) / 2);
//第二行文字长度过半,则截断并且添加省略符
if (layout2.getLineCount() > 1) {
secondLineText = secondLineText.substring(0, layout2.getLineEnd(0)) + "...";
}
resultText = firstLineText + secondLineText ;
}
setText(resultText);
}
}
/**
* @param workingText
* @param width
* @return StaticLayout @See https://developer.android.com/reference/android/text/StaticLayout.html
*/
private Layout createRenderLayout(CharSequence workingText, int width) {
return new StaticLayout(
workingText,
getPaint(),
width,
Alignment.ALIGN_NORMAL,
mLineSpacingMultiplier,
mLineAdditionalVerticalPadding,
false );
}
}