Created
August 20, 2014 09:52
-
-
Save JohnMars/2de495a27aea91bc9199 to your computer and use it in GitHub Desktop.
Android - Expandable Text View
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?xml version="1.0" encoding="utf-8"?> | |
| <resources> | |
| <declare-styleable name="ExpandableTextView"> | |
| <attr name="trimLength" format="integer"/> | |
| </declare-styleable> | |
| </resources> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class ExpandableTextView extends TextView { | |
| private static final int DEFAULT_TRIM_LENGTH = 200; | |
| private static final String ELLIPSIS = "....."; | |
| private CharSequence originalText; | |
| private CharSequence trimmedText; | |
| private BufferType bufferType; | |
| private boolean trim = true; | |
| private int trimLength; | |
| public ExpandableTextView(Context context) { | |
| this(context, null); | |
| } | |
| public ExpandableTextView(Context context, AttributeSet attrs) { | |
| super(context, attrs); | |
| TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpandableTextView); | |
| this.trimLength = typedArray.getInt(R.styleable.ExpandableTextView_trimLength, DEFAULT_TRIM_LENGTH); | |
| typedArray.recycle(); | |
| setOnClickListener(new OnClickListener() { | |
| @Override | |
| public void onClick(View v) { | |
| trim = !trim; | |
| setText(); | |
| requestFocusFromTouch(); | |
| } | |
| }); | |
| } | |
| private void setText() { | |
| super.setText(getDisplayableText(), bufferType); | |
| } | |
| private CharSequence getDisplayableText() { | |
| return trim ? trimmedText : originalText; | |
| } | |
| @Override | |
| public void setText(CharSequence text, TextView.BufferType type) { | |
| originalText = text; | |
| trimmedText = getTrimmedText(text); | |
| bufferType = type; | |
| setText(); | |
| } | |
| private CharSequence getTrimmedText(CharSequence text) { | |
| if (originalText != null && originalText.length() > trimLength) { | |
| return new SpannableStringBuilder(originalText, 0, trimLength + 1).append(ELLIPSIS); | |
| } else { | |
| return originalText; | |
| } | |
| } | |
| public CharSequence getOriginalText() { | |
| return originalText; | |
| } | |
| public void setTrimLength(int trimLength) { | |
| this.trimLength = trimLength; | |
| trimmedText = getTrimmedText(originalText); | |
| setText(); | |
| } | |
| public int getTrimLength() { | |
| return trimLength; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment