I have a TextView
which firstly shows a small portion of a long text.
The user can press a \"see more\" button to expand the TextView
and s
If you want to do it based on the number of lines, here's a way to do it:
(Gist of full code)
/**
* Ellipsize the text when the lines of text exceeds the value provided by {@link #makeExpandable} methods.
* Appends {@link #MORE} or {@link #LESS} as needed.
* TODO: add animation
* Created by vedant on 3/10/15.
*/
public class ExpandableTextView extends TextView {
private static final String TAG = "ExpandableTextView";
private static final String ELLIPSIZE = "... ";
private static final String MORE = "more";
private static final String LESS = "less";
private String mFullText;
private int mMaxLines;
//...constructors...
public void makeExpandable(String fullText, int maxLines) {
mFullText =fullText;
mMaxLines = maxLines;
ViewTreeObserver vto = getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ViewTreeObserver obs = getViewTreeObserver();
obs.removeOnGlobalLayoutListener(this);
if (getLineCount() <= maxLines) {
setText(mFullText);
} else {
setMovementMethod(LinkMovementMethod.getInstance());
showLess();
}
}
});
}
/**
* truncate text and append a clickable {@link #MORE}
*/
private void showLess() {
int lineEndIndex = getLayout().getLineEnd(mMaxLines - 1);
String newText = mFullText.substring(0, lineEndIndex - (ELLIPSIZE.length() + MORE.length() + 1))
+ ELLIPSIZE + MORE;
SpannableStringBuilder builder = new SpannableStringBuilder(newText);
builder.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
showMore();
}
}, newText.length() - MORE.length(), newText.length(), 0);
setText(builder, BufferType.SPANNABLE);
}
/**
* show full text and append a clickable {@link #LESS}
*/
private void showMore() {
// create a text like subText + ELLIPSIZE + MORE
SpannableStringBuilder builder = new SpannableStringBuilder(mFullText + LESS);
builder.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
showLess();
}
}, builder.length() - LESS.length(), builder.length(), 0);
setText(builder, BufferType.SPANNABLE);
}
}
In ListView or RecyclerView instead of using OnGlobalLayoutListener we always use OnPreDrawListener. This callback is fired also for non visible rows at start. From the official documentation:
private void makeTextViewResizable(final TextView tv, final int maxLine, final String expandText, final boolean viewMore){
try {
if (tv.getTag() == null) {
tv.setTag(tv.getText());
}
//OnGlobalLayoutListener
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
ViewTreeObserver obs = tv.getViewTreeObserver();
// obs.removeGlobalOnLayoutListener((ViewTreeObserver.OnGlobalLayoutListener) mActivity);
obs.removeOnPreDrawListener(this);
if (maxLine == 0) {
int lineEndIndex = tv.getLayout().getLineEnd(0);
String text = tv.getText().subSequence(0, lineEndIndex - expandText.length() + 1) + " " + expandText;
tv.setText(text);
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setText(
addClickablePartTextViewResizable(Html.fromHtml(tv.getText().toString()), tv, expandText,
viewMore), TextView.BufferType.SPANNABLE);
} else if (maxLine > 0 && tv.getLineCount() >= maxLine) {
int lineEndIndex = tv.getLayout().getLineEnd(maxLine - 1);
String text = tv.getText().subSequence(0, lineEndIndex - expandText.length() + 1) + " " + expandText;
tv.setText(text);
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setText(
addClickablePartTextViewResizable(Html.fromHtml(tv.getText().toString()), tv, expandText,
viewMore), TextView.BufferType.SPANNABLE);
} else {
int lineEndIndex = tv.getLayout().getLineEnd(tv.getLayout().getLineCount() - 1);
String text = tv.getText().subSequence(0, lineEndIndex) + " " + expandText;
tv.setText(text);
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setText(
addClickablePartTextViewResizable(Html.fromHtml(tv.getText().toString()), tv, expandText,
viewMore), TextView.BufferType.SPANNABLE);
}
return true;
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
Use an ObjectAnimator.
ObjectAnimator animation = ObjectAnimator.ofInt(yourTextView, "maxLines", tv.getLineCount());
animation.setDuration(200).start();
This will fully expand your TextView over 200 milliseconds. You can replace tv.getLineCount()
with however many lines of text you wish to collapse it back down.
----Update----
Here are some convenience methods you can drop in:
private void expandTextView(TextView tv){
ObjectAnimator animation = ObjectAnimator.ofInt(tv, "maxLines", tv.getLineCount());
animation.setDuration(200).start();
}
private void collapseTextView(TextView tv, int numLines){
ObjectAnimator animation = ObjectAnimator.ofInt(tv, "maxLines", numLines);
animation.setDuration(200).start();
}
If you're on API 16+, you can use textView.getMaxLines() to easily determine if your textView has been expanded or not.
private void cycleTextViewExpansion(TextView tv){
int collapsedMaxLines = 3;
ObjectAnimator animation = ObjectAnimator.ofInt(tv, "maxLines",
tv.getMaxLines() == collapsedMaxLines? tv.getLineCount() : collapsedMaxLines);
animation.setDuration(200).start();
}
Notes:
If maxLines has not been set, or you've set the height of your textView in pixels, you can get an ArrayIndexOutOfBounds exception.
The above examples always take 200ms, whether they expand by 3 lines or 400. If you want a consistent rate of expansion, you can do something like this:
int duration = (textView.getLineCount() - collapsedMaxLines) * 10;
Primarily for the case of adding the "See More" to the end of the text, I present to you my TruncatingTextView. After much experimentation it seems to work seamlessly when loading these text views in a RecyclerView item view.
package com.example.android.widgets;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatTextView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.AttributeSet;
import com.example.android.R;
public class TruncatingTextView extends AppCompatTextView {
public static final String TWO_SPACES = " ";
private int truncateAfter = Integer.MAX_VALUE;
private String suffix;
private RelativeSizeSpan truncateTextSpan = new RelativeSizeSpan(0.75f);
private ForegroundColorSpan viewMoreTextSpan = new ForegroundColorSpan(Color.BLUE);
private static final String MORE_STRING = getContext().getString(R.string.more);
private static final String ELLIPSIS = getContext().getString(R.string.ellipsis);
public TruncatingTextView(Context context) {
super(context);
}
public TruncatingTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TruncatingTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setText(CharSequence fullText, @Nullable CharSequence afterTruncation, int truncateAfterLineCount) {
this.suffix = TWO_SPACES + MORE_STRING;
if (!TextUtils.isEmpty(afterTruncation)) {
suffix += TWO_SPACES + afterTruncation;
}
// Don't call setMaxLines() unless we have to, since it does a redraw.
if (this.truncateAfter != truncateAfterLineCount) {
this.truncateAfter = truncateAfterLineCount;
setMaxLines(truncateAfter);
}
setText(fullText);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (getLayout() != null && getLayout().getLineCount() > truncateAfter) {
int lastCharToShowOfFullTextAfterTruncation = getLayout().getLineVisibleEnd(truncateAfter - 1) - suffix.length() - ELLIPSIS.length();
if (getText().length() <= lastCharToShowOfFullTextAfterTruncation) {
// No idea why this would be the case, but to prevent a crash, here it is. Besides, if this is true, we should be less than our maximum lines and thus good to go.
return;
}
int startIndexOfMoreString = lastCharToShowOfFullTextAfterTruncation + TWO_SPACES.length() + 1;
SpannableString truncatedSpannableString = new SpannableString(getText().subSequence(0, lastCharToShowOfFullTextAfterTruncation) + ELLIPSIS + suffix);
truncatedSpannableString.setSpan(truncateTextSpan, startIndexOfMoreString, truncatedSpannableString.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
truncatedSpannableString.setSpan(viewMoreTextSpan, startIndexOfMoreString, startIndexOfMoreString + MORE_STRING.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
setText(truncatedSpannableString);
}
}
}
You can always choose to add your own attribute for truncateAfter, and use any of the above answers to add the animation for expand/collapse (I did not code to handle expand/collapse but easily done by using one of the above animation answers).
I'm placing this here more for others who are trying to find "View More" functionality for their text views.
Smooth expanding (using heigh & ObjectAnimator)
FYI: requires API 11
public static void expandCollapsedByMaxLines(@NonNull final TextView text) {
final int height = text.getMeasuredHeight();
text.setHeight(height);
text.setMaxLines(Integer.MAX_VALUE); //expand fully
text.measure(View.MeasureSpec.makeMeasureSpec(text.getMeasuredWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED));
final int newHeight = text.getMeasuredHeight();
ObjectAnimator animation = ObjectAnimator.ofInt(text, "height", height, newHeight);
animation.setDuration(250).start();
}
P.S. I assume TextView limited by maxLines.
P.S.S. Thanks Amagi82 for ObjectAnimator example
Cliffus' answer came close to what I was looking for, but it doesn't support using the setMaxLines()
method, which causes issues when you can't set the max lines through XML.
I've forked their library and made it so that using setMaxLines()
won't break the expand/collapse action. I also updated the Gradle configuration and migrated it to AndroidX. Otherwise, the usage is the same as before.
You can include it in your project using Jitpack:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
dependencies {
implementation 'com.github.zacharee:Android-ExpandableTextView:Tag'
}
Where Tag
is the latest commit tag (https://jitpack.io/#zacharee/Android-ExpandableTextView/).
The usage is exactly the same as the original library's. Include the ExpandableTextView in your XML:
<at.blogc.android.views.ExpandableTextView
...
android:maxLines="10"
/>
And expand/collapse in code:
if (expandable.isExpanded) {
expandable.collapse()
else {
expandable.expand()
}