从适配器启动的 AsyncTask 更新文本视图 (getView)



我从AsynTask更新TextView时遇到了一个奇怪的问题。在我的适配器的getView函数中,我启动了一个AsyncTask,以计算一个数字并将其显示在屏幕上。

问题是 getView 函数对单个项目被调用了多次,因此计算的是我想显示的数字的几倍,效率不是很高。

我被调查并意识到,每当我尝试限制对 AsyncTask 的操作系统调用次数时,该数字都不会显示在屏幕上(没有错误消息或异常)

public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.category_item, null);
    TextView tvCategory = (TextView) rowView.findViewById(R.id.tvCategory);
    TextView tvUnreadNews = (TextView) rowView.findViewById(R.id.tvUnreadNews);
    Category cat = mCategoriesList.get(position);
    tvCategory.setText(cat.getName());
    if(!cat.isInitialized()) //<-- If I delete this line it works, but inefficienly, as the AsyncTask is launched many times repeatedly
    {
            cat.setIsInitialized(true)
        new GetNewsForCategoryTask(cat, tvUnreadNews, mContext).execute(cat.getId());
    }
    return rowView;
}

这是AsyncTask。重复调用时正确更新文本视图,但在仅对类别调用一次时不更新值:

public class GetNewsForCategoryTask extends AsyncTask<String, Integer, JSONArray>{
private Context mContext;
private String mCategoryId;
private TextView mTvUnread;
private Category mCategory;
public GetNewsForCategoryTask(Category cat, TextView tvUnread, Context context) {
    mTvUnread = tvUnread;
    mCategory = cat;
    mContext = context;
}
@Override
protected JSONArray doInBackground(String... params) {
    mCategoryId = params[0];
     ...
}
@Override
protected void onProgressUpdate(Integer... values) {
    mTvUnread.setText(Integer.toString(values[0]));
}
@Override
protected void onPostExecute(JSONArray result) {
    if(result != null && mThrown == null)
    {
        publishProgress(mCategory.getUnreadNewsSet().size());
    }
}

}

有没有人会做出这种奇怪的行为的原因?我检查了 AsyncTask 在仅启动一次专业类别时是否正确调用,但只是不更新布局。为什么要推出多次专业类别有效?

更新:我一直在测试,看起来问题出在 getView() 函数上。如果我检查变量是否已初始化,则只有 ListView 的第一个元素会更改......与列表视图中其他项目的所有值!!

所以看起来文本视图正在尝试设置的值始终是第一个(列表视图的第一个元素)。

有什么想法吗???

看看这个:

Category cat = mCategoriesList.get(position);
tvCategory.setText(cat.getName());
if(!cat.isInitialized()) //<-- If I delete this line it works, but inefficienly, as the AsyncTask is launched many times repeatedly
{
    cat.setIsInitialized(true)
    new GetNewsForCategoryTask(cat, tvUnreadNews, mContext).execute(cat.getId());
}

我认为您必须在 mCategoriesList.get(position) 上调用 setIsInitialized(true),而不是在 cat 上调用,因为当再次调用getView()时,mCategoriesList.get(position)总是返回未初始化的 ,因为您在 cat 上调用setIsInitialized(true),而不是在mCategoriesList中。

相关内容

最新更新