o9s
is a microblog
home archives search feed blogroll


ShowMoreTextView

/**
 * A text view with a 'More...' button when the text is too long.
 */

public class ShowMoreTextView extends AppCompatTextView {

    private static final int TEXT_MAX_LENGTH = 200;

    public ShowMoreTextView(Context context) {
        super(context);
        setMovementMethod(LinkMovementMethod.getInstance());
    }

    public ShowMoreTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setMovementMethod(LinkMovementMethod.getInstance());
    }

    public ShowMoreTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setMovementMethod(LinkMovementMethod.getInstance());
    }

    public void setShortened(final CharSequence sequence) {
        if (sequence != null && sequence.length() > TEXT_MAX_LENGTH) {
            CharSequence text = sequence.subSequence(0, TEXT_MAX_LENGTH - 3) + "... ";
            String more = getContext().getString(R.string.more);
            SpannableString ss = new SpannableString(text + more);

            ss.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View textView) {
                    setFullened(sequence);
                }
            }, ss.length() - more.length(), ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            setText(ss);
        } else {
            setText(sequence);
        }
    }

    private void setFullened(final CharSequence sequence) {
        String less = getContext().getString(R.string.less);
        SpannableString ss = new SpannableString(sequence + " " + less);

        ss.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View textView) {
                setShortened(sequence);
            }
        }, ss.length() - less.length(), ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        setText(ss);
    }

}

Don’t forget to add more’ and less’ to strings.xml.

Posted on 2018-04-25   #android     #java  






← Next post    ·    Previous post →