将长文本分隔为viewpager的页面

Pha*_*inh 4 java string android text character

我在这个问题中实现了messureText方法,以便在viewpager中呈现之前将长文本分隔成具有指定大小的页面.我正在做一个带有增量字符数的while循环来获得所需的文本块,但它似乎不是最好的解决方案.是否有任何建议可以改善此计算的性能?p/s:我指的是Wattpad应用程序看到它做得这么快但不知道怎么做?

小智 6

StaticLayoutDynamicLayout可以做到这一点.Android使用(Boring | Static | Dynamic)布局类来测量和包装文本,这些类构造函数将CharSequence作为输入参数,因此样式文本(包含跨度,甚至ImageSpan)是可以接受的.您可以根据视图或屏幕计算pageWidth和pageHeight,TextPaint和两个lineSpacing参数必须等于您的目标TextView,这是我的代码:

import android.text.Layout;
import android.text.SpannableStringBuilder;
import android.text.StaticLayout;
import android.text.TextPaint;

import java.util.ArrayList;
import java.util.List;

public class PageSplitter {
    private final int pageWidth;
    private final int pageHeight;
    private final float lineSpacingMultiplier;
    private final float lineSpacingExtra;
    private final List<CharSequence> pages = new ArrayList<CharSequence>();
    private SpannableStringBuilder mSpannableStringBuilder = new SpannableStringBuilder();

    public PageSplitter(int pageWidth, int pageHeight, float lineSpacingMultiplier, float lineSpacingExtra) {
        this.pageWidth = pageWidth;
        this.pageHeight = pageHeight;
        this.lineSpacingMultiplier = lineSpacingMultiplier;
        this.lineSpacingExtra = lineSpacingExtra;
    }

    public void append(CharSequence charSequence) {
        mSpannableStringBuilder.append(charSequence);
    }

    public void split(TextPaint textPaint) {
        StaticLayout staticLayout = new StaticLayout(
                mSpannableStringBuilder,
                textPaint,
                pageWidth,
                Layout.Alignment.ALIGN_NORMAL,
                lineSpacingMultiplier,
                lineSpacingExtra,
                false
        );
        int startLine = 0;
        while(startLine < staticLayout.getLineCount()) {
            int startLineTop = staticLayout.getLineTop(startLine);
            int endLine = staticLayout.getLineForVertical(startLineTop + pageHeight);
            int endLineBottom = staticLayout.getLineBottom(endLine);
            int lastFullyVisibleLine;
            if(endLineBottom > startLineTop + pageHeight)
                lastFullyVisibleLine = endLine - 1;
            else
                lastFullyVisibleLine = endLine;
            int startOffset = staticLayout.getLineStart(startLine);
            int endOffset = staticLayout.getLineEnd(lastFullyVisibleLine);
            pages.add(mSpannableStringBuilder.subSequence(startOffset, endOffset));
            startLine = lastFullyVisibleLine + 1;
        }
    }

    public List<CharSequence> getPages() {
        return pages;
    }
}
Run Code Online (Sandbox Code Playgroud)