我正在开发一个应用程序,它经常需要在TextView中向用户显示结果,就像某种日志一样.
该应用程序运行良好,它在TextView中显示结果,但只要它继续运行和添加行,应用程序变慢,崩溃,因为TextView的字符长度.
我想知道android API是否提供了强制TexView自动删除引入的最旧行以便为新的行腾出空间的任何方法.
我有同样的问题.我刚解决了.
诀窍是使用getEditableText()TextView 的方法.它有一种replace()方法,甚至一种方法delete().当您在其中附加行时,TextView已标记为"可编辑",需要使用它getEditableText().我有类似的东西:
private final static int MAX_LINE = 50;
private TextView _debugTextView; // Of course, must be filled with your TextView
public void writeTerminal(String data) {
_debugTextView.append(data);
// Erase excessive lines
int excessLineNumber = _debugTextView.getLineCount() - MAX_LINE;
if (excessLineNumber > 0) {
int eolIndex = -1;
CharSequence charSequence = _debugTextView.getText();
for(int i=0; i<excessLineNumber; i++) {
do {
eolIndex++;
} while(eolIndex < charSequence.length() && charSequence.charAt(eolIndex) != '\n');
}
if (eolIndex < charSequence.length()) {
_debugTextView.getEditableText().delete(0, eolIndex+1);
}
else {
_debugTextView.setText("");
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,TextView.getLineCount()返回包装行的数量,而不是文本中"\n"的数量......这就是为什么如果我在寻找删除行时到达文本的末尾我清除整个文本的原因.
您可以通过删除多个字符而不是删除多行来实现不同的操作.
小智 8
此解决方案跟踪列表中的日志行,并在每次更改时使用列表内容覆盖textview.
private List<String> errorLog = new ArrayList<String>();
private static final int MAX_ERROR_LINES = 70;
private TextView logTextView;
public void addToLog(String str) {
if (str.length() > 0) {
errorLog.add( str) ;
}
// remove the first line if log is too large
if (errorLog.size() >= MAX_ERROR_LINES) {
errorLog.remove(0);
}
updateLog();
}
private void updateLog() {
String log = "";
for (String str : errorLog) {
log += str + "\n";
}
logTextView.setText(log);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13928 次 |
| 最近记录: |