This is how i have achieved the desired output,
MytextView which i want to expand is: tvDescription
I have a see more button with name: btnSeeMore
To check if the textview has more than 4 lines i had a listener for it as follows,
tvDescription.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if(expandable) {
expandable = false;
if (tvDescription.getLineCount() > 4) {
btnSeeMore.setVisibility(View.VISIBLE);
ObjectAnimator animation = ObjectAnimator.ofInt(tvDescription, "maxLines", 4);
animation.setDuration(0).start();
}
}
}
});
I have kept a boolean value to check if textview is already expanded so that there will not be any hickups while collapsing it.
if textview has more than four lines, boolean flag will be true and the button will be visible so this is the code for expanding and collapsing animation.
btnSeeMore.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!expand) {
expand = true;
ObjectAnimator animation = ObjectAnimator.ofInt(tvDescription, "maxLines", 40);
animation.setDuration(100).start();
btnSeeMore.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.ic_collapse));
} else {
expand = false;
ObjectAnimator animation = ObjectAnimator.ofInt(tvDescription, "maxLines", 4);
animation.setDuration(100).start();
btnSeeMore.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.drawable.ic_expand));
}
}
});
Comment below for further information