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
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;