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;
public class CustomWidgetTextView extends TextView { private float mLineSpacingMultiplier = 1.0f; private float mLineAdditionalVerticalPadding = 0.0f;
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); }
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); } }
private Layout createRenderLayout(CharSequence workingText, int width) { return new StaticLayout( workingText, getPaint(), width, Alignment.ALIGN_NORMAL, mLineSpacingMultiplier, mLineAdditionalVerticalPadding, false ); } }
|