是否可以在不分配额外内存的情况下不断更新 TextView 文本?
我已经实现了一个经过时间计数器,它使用 TextView
来显示经过的时间,精确到百分之一秒。每次更新时,我当前的实现都会读取经过的时间,分配一个新的 String
格式为用户可读的,并使用此 String
更新 TextView
文本代码>.
每个String
只在一小部分时间内使用一次,然后很快就被永远丢弃,这似乎是对内存的巨大浪费。有没有办法连续更新 TextView
文本,而无需每次为新的 String
分配额外的内存?
这是我当前用来格式化文本的方法:
public static String formatTime(long time) {
int minute = (int) (time / 60000);
int second = (int) (time / 1000) % 60;
int hundredth = (int) (time / 10) % 100;
return String.format("%02d:%02d:%02d", minute, second, hundredth);
}
调用函数计算经过的时间,调用此函数,然后立即调用 TextView
上的 setText(String)
。
I have implemented an elapsed time counter that uses a TextView
to display elapsed time down to hundredths of a second. On each update, my current implementation reads the elapsed time, allocates a new String
formatted to be user-readable, and updates the TextView
text with this String
.
It seems like a huge waste of memory that each String
is used only once for a tiny fraction of a second and then quickly discarded forever. Is there a way to continuously update the TextView
text without allocating additional memory for a new String
each time?
Here is the method I am currently using to format my text:
public static String formatTime(long time) {
int minute = (int) (time / 60000);
int second = (int) (time / 1000) % 60;
int hundredth = (int) (time / 10) % 100;
return String.format("%02d:%02d:%02d", minute, second, hundredth);
}
The calling function calculates the elapsed time, calls this function, and then immediately calls setText(String)
on the TextView
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你做得很好。如果您确实想避免分配字符串,请尝试 StringBuffer。但随后您必须放弃
format
api 并自行完成所有操作,这可能不会像您想象的那样执行。此外,您当前的实现使其线程安全。I think you are doing a good job. If you really want to do avoid allocation string try StringBuffer. But then you have to let go the the
format
api and do everything urself which may not be as performing as you think. Also your current implementation makes it thread safe.在浏览 setText() 方法的文档时,我注意到该方法签名是..
在进一步挖掘时,我发现 StringBuilder 还实现了 CharSequence 接口。
所以我想解决方案是
开始使用 StringBuilder 而不是 String
对象。我唯一担心的是 String.format() 方法不能再使用,所以我们必须开始使用 Formatter 类。
更多信息可以在这里找到格式化程序类。
我希望它有帮助...
On going through the documentation on the setText() method, I noticed that the method signature is..
On digging further I discovered that StringBuilder also implements the CharSequence interface.
So I guess a solution would be to
start using StringBuilder instead of the String
object.The only concern left for me is the String.format() method can no longer be used, so we have to start using the Formatter class.
more info can be found here Formatter Class.
I hope it helps...