【问题标题】:If a text in a TextView is longer than the available space, how to get the remaining lines?如果 TextView 中的文本长于可用空间,如何获取剩余的行?
【发布时间】:2011-04-16 19:37:42
【问题描述】:

我有一个长文本,我希望它与 TextView 一起显示。我拥有的文本比可用空间长得多。但是我不想使用滚动,而是 ViewFlipper 来翻到下一页。如何从第一个 TextView 中检索由于视图太短而未显示的行,以便我可以将它们粘贴到下一个 TextView 中?

编辑:我找到了我的问题的解决方案。我只需要像这样使用带有 StaticLayout 的自定义视图:

public ReaderColumView(Context context, Typeface typeface, String cText) {
        super(context);
        Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        dWidth = display.getWidth(); 
        dHeight = display.getHeight();

        contentText = cText;

        tp = new TextPaint();
        tp.setTypeface(typeface);
        tp.setTextSize(25);
        tp.setColor(Color.BLACK);
        tp.setAntiAlias(true);

        StaticLayout measureLayout = new StaticLayout(contentText, tp, 440, Alignment.ALIGN_NORMAL, 1, 2, true);
        Boolean reachedEndOfScreen = false;
        int line = 0;
        while (!reachedEndOfScreen) {
            if (measureLayout.getLineBottom(line) > dHeight-30) {
            reachedEndOfScreen = true;
            fittedText = contentText.substring(0, measureLayout.getLineEnd(line-1));
            setLeftoverText(contentText.substring(measureLayout.getLineEnd(line-1)));
            }

            line++;

        }
    }
protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        StaticLayout textLayout = new  StaticLayout(fittedText, tp, 440, Alignment.ALIGN_NORMAL, 1, 2, true);
        canvas.translate(20,20);
        textLayout.draw(canvas);
    }

这还没有优化,但你明白了。 我希望它可以帮助像我这样有类似问题的人。

【问题讨论】:

  • 您应该考虑一个自我回答的问题。否则不清楚是否有答案。
  • 你不应该在onDraw期间创建StaticLayout,它非常昂贵,尤其是对于长文本。

标签: android android-widget


【解决方案1】:

在您的回答中,您可以使用 StaticLayout 来测量和绘制文本。然而,

  • 您不应该在 onDraw 期间创建 StaticLayout,它非常昂贵,尤其是对于长文本。相反,您应该在 onMeasure 期间创建一次并重复使用它。
  • 对于寻找要结束的行的 while 循环 (while (!reachedEndOfScreen)),您可以使用 StaticLayout.getLineForVertical(int offset)。
  • 您可以使用索引而不是子字符串或 leftOverText,并将这些索引传递给每个页面的 StaticLayout。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多