gpt4 book ai didi

android - 如何异步设置 TextView 的文本?

转载 作者:太空狗 更新时间:2023-10-29 14:26:56 24 4
gpt4 key购买 nike

我必须用需要时间收集的文本信息填充 ListView。我的方法是使用 AsyncTask 来完成后台作业,但是当结果到达时将文本设置为 TextView 会减慢列表速度:每次调用 getView() 时列表都会滞后。

这是我的 AsyncTask

private class BreadcrumbTask extends AsyncTask<FFile, Void, String>{
private WeakReference<TextView> mTextView;
public BreadcrumbTask(TextView textView){
mTextView = new WeakReference<TextView>(textView);
}

@Override
protected String doInBackground(FFile... params) {
// text processing
}

@Override
protected void onPostExecute(String result) {
if (mTextView != null){
TextView tv = mTextView.get();
if (tv != null)
//this line blocks the UI. if I comment it the lag is gone
tv.setText(result);
}

//mTextView.setText(结果);

我在 getView() 中创建了一个新任务并执行它。问题显然来自 onPostExecute() 中的 tv.setText(result)。当我发表评论时,列表流动得很好。那么,如何在不减慢 UI 的情况下更新 TextView

最佳答案

使用 ViewHolder模式。

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

在 View 持有者中持有 View 对象

您的代码可能会在 ListView 滚动期间频繁调用 findViewById(),这会降低性能。即使当 Adapter 返回一个膨胀的 View 以供回收时,您仍然需要查找元素并更新它们。避免重复使用 findViewById() 的一种方法是使用“ View 持有者”设计模式。

A ViewHolder object stores each of the component views inside the tag field of the Layout, so you can immediately access them without the need to look them up repeatedly. First, you need to create a class to hold your exact set of views. For example:

static class ViewHolder {
TextView text;
TextView timestamp;
ImageView icon;
ProgressBar progress;
int position;
}

Then populate the ViewHolder and store it inside the layout.

ViewHolder holder = new ViewHolder();
holder.icon = (ImageView) convertView.findViewById(R.id.listitem_image);
holder.text = (TextView) convertView.findViewById(R.id.listitem_text);
holder.timestamp = (TextView) convertView.findViewById(R.id.listitem_timestamp);
holder.progress = (ProgressBar) convertView.findViewById(R.id.progress_spinner);
convertView.setTag(holder);

其他一些例子:

http://xjaphx.wordpress.com/2011/06/16/viewholder-pattern-caching-view-efficiently http://www.jmanzano.es/blog/?p=166

关于android - 如何异步设置 TextView 的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11456828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com