获取textview行数
textview
代码
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 );
}
}
转载于:https://www.cnblogs.com/jasonkent27/p/5642790.html
相关资源:DirectX修复工具V4.0增强版