【发布时间】:2016-03-28 18:52:57
【问题描述】:
我需要显示大型文本文件。无需滚动即可显示文本作为电子书。我可以打断页面上的长文本,但这需要我太多时间。例如 - 以下代码处理 1.4 MB 的文本大约 10-15 秒。
public void split(TextPaint textPaint, String filepath,Context context) {
int pages = 0;
File file = new File(filepath);
char[] bufferChar = new char[1024];
String uncompletedtext="";
//How lines we can show
int maxLinesOnpage = 0;
StaticLayout staticLayout = new StaticLayout(
context.getString(R.string.lorem_ipsum),
textPaint,
pageWidth,
Layout.Alignment.ALIGN_NORMAL,
lineSpacingMultiplier,
lineSpacingExtra,
false
);
int startLineTop = staticLayout.getLineTop(0);
int endLine = staticLayout.getLineForVertical(startLineTop + pageHeight);
int endLineBottom = staticLayout.getLineBottom(endLine);
if (endLineBottom > startLineTop + pageHeight) {
maxLinesOnpage = endLine - 1;
} else {
maxLinesOnpage = endLine;
}
//let's paginate
try {
BufferedReader buffer = new BufferedReader(new FileReader(file));
while (buffer.read(bufferChar)>=0) {
uncompletedtext += new String(bufferChar);
boolean allcomplete = false;
staticLayout = new StaticLayout(
uncompletedtext,
textPaint,
pageWidth,
Layout.Alignment.ALIGN_NORMAL,
lineSpacingMultiplier,
lineSpacingExtra,
false
);
staticLayout.getLineCount();
int curTextPages= (int) Math.floor(staticLayout.getLineCount() / maxLinesOnpage);
uncompletedtext=uncompletedtext.substring(staticLayout.getLineEnd(curTextPages));
pages+=curTextPages;
Log.e("PAGES","" + pages);
}
} catch (Exception e) {
e.printStackTrace();
}
Log.e("FILE READED FULLY!!", "READ COMPLETE!!!!!!!!!!!!!!!!");
}
太长了。我无法理解 FBReader 和СoolReader 等应用程序如何立即处理大文件(超过 9 MB)。 我看到了应用程序的来源,但它们的功能太多,无法快速找到答案。 我真的需要帮助和提示。谢谢。
【问题讨论】:
-
对Paginating text in Android有帮助吗?...
-
这是一个很好的解决方案,但不适用于大文本。
-
在每个
while (buffer.read(bufferChar)>=0)循环迭代中创建一个新的StaticLayout实例。这是一项昂贵的操作,可能会导致性能问题。 -
是的,你是对的。我找到解决方案。需要使用
RandomAccessFile。
标签: java android pagination