我有一个TextView
,用于显示链接越来越少的大型文本。我的TextView
适配器中有RecyclerView
。当我启动应用程序时,它会显示正确的文本,但是当我向下滚动并再次向上滚动时,有时文本会消失,有时文本会被交换,有时它不再出现。
我使用以下代码:
CreateView Holder代码:
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
return new ListItemHolder(inflater.inflate(mLayoutResID, viewGroup, false));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int position) {
mList = (dataList) this.dataList.get(position);
final ListItemHolder listItemHolder = (ListItemHolder) viewHolder;
listItemHolder.mBodyText = mList.getmBody();
makeExpandable(listItemHolder.mBodyText, listItemHolder.mBodyTextView);
}
public void makeExpandable(String descriptionText, final TextView textView) {
MORE = mContext.getResources().getString(R.string.more_content);
LESS = " " + mContext.getResources().getString(R.string.less_content);
CharSequence body = Html.fromHtml(descriptionText);
final SpannableString text = new SpannableString(body);
mTitleBodyTextView = textView;
final int maxChar = 150;
final ViewTreeObserver vto = textView.getViewTreeObserver();
textView.setTextColor(mContext.getResources().getColor(R.color.black));
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
ViewTreeObserver obs = textView.getViewTreeObserver();
obs.removeOnGlobalLayoutListener(this);
lineEndIndex = 150;
textView.setMovementMethod(LinkMovementMethod.getInstance());
showLess(text, maxChar, textView);
}
});
}
/**
* truncate text and append a clickable {@link #MORE}
*/
private void showLess(final SpannableString text, final int maxChar, final TextView textView) {
final String newText = text.subSequence(0, lineEndIndex - (ELLIPSIZE.length() +
MORE.length() + 1)).toString() + ELLIPSIZE + MORE;
SpannableStringBuilder builder = new SpannableStringBuilder(newText);
builder.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
showMore(text, maxChar, textView);
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
ds.setColor(mContext.getResources().getColor(R.color.grey_dark));
}
}, newText.length() - MORE.length(), newText.length(), 0);
textView.setText(builder, TextView.BufferType.SPANNABLE);
}
/**
* show full text and append a clickable {@link #LESS}
*/
private void showMore(final SpannableString text, final int maxChar, final TextView textView) {
// create a text like subText + ELLIPSIZE + MORE
SpannableStringBuilder builder = new SpannableStringBuilder(text + LESS);
builder.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
showLess(text, maxChar, textView);
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
ds.setColor(mContext.getResources().getColor(R.color.grey_dark));
}
}, builder.length() - LESS.length(), builder.length(), 0);
textView.setText(builder, TextView.BufferType.SPANNABLE);
}