android - 如何对长文本进行分页?

标签 android text

我有一个长文本和固定大小的 textView。如何逐页显示文本?用户将以这种方式与程序交互: 他向左或向右滑动以翻到下一页或上一页。

目前,我创建了一个 PageManager 来完成这项工作。但它非常有限。处理文本的核心代码是:

while (true) {
        newLineIndex = TextUtils.indexOf(content, '\n', processIndex);
        if (newLineIndex == -1) {// till the end of content
            charCount = paint.breakText(content, processIndex, content.length(), false, leftLines * lineWidth, width);
        } else {
            charCount = paint.breakText(content, processIndex, ++newLineIndex, false, leftLines * lineWidth, width);
        }

        leftLines = (int) ((leftLines * lineWidth - width[0]) / lineWidth);
        processIndex += charCount;

        if (leftLines < 1 || processIndex >= content.length()) {
            page = new Page();
            page.endIndex = processIndex;
            page.startIndex = pageBaseLine;
            page.content = content.subSequence(page.startIndex, page.endIndex);
            result.add(page);
            pageBaseLine = processIndex;

            leftLines = lineNumber;
        }

        if (processIndex >= content.length()) {
            break;
        }
    }

限制是页面可能会像

那样截断文本
|A lon|
|g wor|
|d man|

//一个长字男人

或由于自动换行导致的错误行:

//Page Manager 计算这个(2 行):

|a sentence with loooooooo|

|ooong word abcdefghijklmn|

//但实际上在 TextView 中(3行):

|a sentence with           |

|looooooooooong word      |

|abcdefghijklmn           |

所以最后的行数比计算还多。所以我的页面管理员很愚蠢。有人会帮助我吗?谢谢!

最佳答案

现在回答可能为时已晚,但我会发布我是如何解决这样的问题的。

我做了类似的项目,但针对的是安卓平板电脑。在我的应用程序中,我有系统底栏、导航栏和标题。 Activity的这些部分不参与文本预览,所以我想在计算中排除它们。对于 750px 的屏幕,这些部分占屏幕的 24%,约为 180px。所以我使用以下算法在 TextView 中查看文本:

  1. 计算实际高度以查看文本,它是我的 TextView 的高度:ScreenHeight - ScreenHeight*0.24
  2. 设置文字大小,例如14.0
  3. 计算文本文件中的行数
  4. 计算每页行数:实际高度/文字大小
  5. 计算页数并加载到HashMap中

Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight() — 0.24*display.getHeight();
mLinesInPage = (int) (Math.floor(height / mTextSize));
mPages = (int) (Math.ceil(mLinesInText / mLinesInPage));

格式化和其他转换“即时”执行。没什么困难,但对我有用。有例子

在使用算法之前:

enter image description here

使用算法后:

enter image description here

enter image description here

关于android - 如何对长文本进行分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8368448/

相关文章:

Android:获取用户代理对象中设置的json对象

Android - 线程中的 Looper.prepare() 与 Activity.runOnUIThread()

Linux shell命令将文本数据从一个文件复制到另一个

python - 如何使用基本库计算此类列表的频率?

javascript - JS 鼠标悬停时文本发生变化

html - 如果长度超过表格单元格宽度,则将文本截断到最后一个单词

javascript - 获取 innerHTML 值 - 仅纯文本

android - 如何覆盖 android 样式的私有(private)属性

java - 确定设备存储空间不工作 : android

android - 如何在 ARCore 中检测眼睛的 Vetcor3 点或区域类型