I want to add "..more" at end of 3rd line for textview and if we click on more we will show full text in pop up (or custom dialog). So I used below code for this functionality. The code is working fine when you are in portrait mode but when you change device orientation it's not working. And I am using BaseAdapter and RecyclerView (by using ViewHelper design pattern).
public interface ViewMoreClickListener {
void viewMoreClicked(int index);
}
public void addViewMoreToTextView(final int position, final TextView tv, final String expandText, final int maxLine, final ViewMoreClickListener listener) {
try {
if (tv.getTag() == null) {
tv.setTag(tv.getText());
}
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {
ViewTreeObserver obs = tv.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
String text = tv.getText().toString();
if (tv.getLineCount() > maxLine) {
int lineEndIndex = tv.getLayout().getLineEnd(maxLine - 1);
text = text.subSequence(0, lineEndIndex - expandText.length() + 1) + " " + expandText;
tv.setText(text);
// We are rechecking in order to resolve issue with alignment problem
if (tv.getLineCount() > maxLine) {
lineEndIndex = tv.getLayout().getLineEnd(maxLine - 1);
text = text.subSequence(0, lineEndIndex - expandText.length() + 1) + " " + expandText;
tv.setText(text);
}
tv.setMovementMethod(LinkMovementMethod.getInstance());
String str = Html.fromHtml(text).toString();
SpannableStringBuilder ssb = new SpannableStringBuilder(Html.fromHtml(text));
if (str.contains(expandText)) {
ssb.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
if (listener != null)
listener.viewMoreClicked(position);
}
}, str.indexOf(expandText), str.indexOf(expandText) + expandText.length(), 0);
}
tv.setText(ssb);
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public class SampleActivity extends BaseActivity implements ViewMoreClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void viewMoreClicked(int index) {
// here we will show full text in pop up or custom dialog by getting from arraylist based on index.
}
}
And I am calling the above method from getView() of adapter.
addViewMoreToTextView(position, textview, "..more", 3, listener);
I have gone thorough these links but they also are not working in RecyclerView.
Add "View More" at the end of textview after 3 lines
Set Text View ellipsize and add view more at end
Please help me to resolve this issue.