如何在列表视图项中添加readmore文本?

时间:2018-10-11 05:26:58

标签: android listview

我在listview项目中添加了readmore文本,但listitem onclick侦听器不起作用。它仅在listview项目文本区域有效,而不适用于listitem的整行。

1 个答案:

答案 0 :(得分:0)

创建自定义TextView并像这样使用

public class ReadMoreTextView extends TextView {
 private static final int DEFAULT_TRIM_LENGTH = 90;
 private static final String ELLIPSIS ="<html><body><font 
                         color='#ff1493'>... 
                         (Read More)</font></body></html>";

private CharSequence originalText;
private CharSequence trimmedText;
private BufferType bufferType;
private boolean trim = true;
private int trimLength;

public ReadMoreTextView(Context context) {
    this(context, null);
}

public ReadMoreTextView(final Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray typedArray = context.obtainStyledAttributes(attrs, 
         R.styleable.ExpandableTextView);
    this.trimLength = 
      typedArray.getInt(R.styleable.ExpandableTextView_trimLength, 
        DEFAULT_TRIM_LENGTH);
    typedArray.recycle();
}

  private void setText() {
    super.setText(getDisplayableText(), bufferType);
 }

  private CharSequence getDisplayableText() {
    return trim ? trimmedText : originalText;
 }

@Override
public void setText(CharSequence text, BufferType type) {
    originalText = text;
    trimmedText = getTrimmedText(text);
    bufferType = type;
    setText();
}

private CharSequence getTrimmedText(CharSequence text) {
    if (originalText != null && originalText.length() > trimLength) {
        return new SpannableStringBuilder(originalText, 0, trimLength + 
        1).append(Html.fromHtml(ELLIPSIS));
    } else {
        return originalText;
    }
}

public CharSequence getOriginalText() {
    return originalText;
}

public void setTrimLength(int trimLength) {
    this.trimLength = trimLength;
    trimmedText = getTrimmedText(originalText);
    setText();
}

public int getTrimLength() {
    return trimLength;
}
}

并在xml中使用

  <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/btnTextClick">

            <com.example.ReadMoreTextView
                android:id="@+id/tvD"
                android:layout_width="wrap_content"
                android:clickable="false"
                android:layout_height="wrap_content"
                android:maxLines="3"/>
        </FrameLayout>