我有一个长文本和固定大小的 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 中查看文本:
- 计算实际高度以查看文本,它是我的 TextView 的高度:ScreenHeight - ScreenHeight*0.24
- 设置文字大小,例如14.0
- 计算文本文件中的行数
- 计算每页行数:实际高度/文字大小
- 计算页数并加载到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));
格式化和其他转换“即时”执行。没什么困难,但对我有用。有例子
在使用算法之前:
使用算法后:
关于android - 如何对长文本进行分页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8368448/