gpt4 book ai didi

android - 在 RecyclerView 中更新 ProgressBar

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:11:01 34 4
gpt4 key购买 nike

我有一个 RecyclerView。其中,项目具有标准布局 - 一个 TextView 和一个 ProgressBar。项目在运行时添加到 recyclerview。每当添加一个 Item 时,都会启动一个 AsyncTask 来更新 ProgressBar。AsynTask 持有对来自 RecyclerView Adapter 的 ProgressBar 对象的引用。当回收站 View 中的项目过多时会出现此问题。

我知道 RecyclerView 会回收任何旧 View ,因此至少要为进度条找到解决方法。

实现它的理想方式是什么?

以下是适配器的摘录

public class RecViewAdapter extends
RecyclerView.Adapter<RecViewAdapter.ViewHolder> {
Context mContext;
List<String> mRunns;
static ExecutorService mExec;
static HashSet<Integer> mProcessed = new HashSet<>();

public RecViewAdapter(Context context, List<String> runns) {
mContext = context;
mRunns = runns;
mExec = Executors.newFixedThreadPool(1);
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.runnabel_item, viewGroup,
false);
ViewHolder vh = new ViewHolder(v);
return vh;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.runnName.setText(mRunns.get(position));
if (!mProcessed.contains(position)) {
new ProgressTask(holder.pBar, position).executeOnExecutor(mExec, null);
mProcessed.add(position);
}
}

@Override
public int getItemCount() {
return mRunns.size();
}

public static class ViewHolder extends RecyclerView.ViewHolder {
TextView runnName;
ProgressBar pBar;

public ViewHolder(View view) {
super(view);
runnName = (TextView) view.findViewById(R.id.textView);
pBar = (ProgressBar) view.findViewById(R.id.progressBar);
pBar.setIndeterminate(false);
pBar.setMax(100);
pBar.setProgress(0);

}
}
}

此外,我正在使用 notifydatasetchanged 将项目添加到 RecyclerView。

最佳答案

您可以简单地使用回收 View 的“findViewHolderForAdapterPosition”方法,您将从中获得一个 viewHolder 对象,然后将该 viewHolder 类型转换为您的适配器 View ,这样您就可以直接访问您的 View ,(在本例中我们访问 progressBar)

以下是kotlin的示例代码

 /**
* update progress bar in recycler view
* get viewHolder from position and progress bar from that viewHolder
* we are rapidly updating progressbar so we did't use notify method as it always update whole row instead of only progress bar
* @param position : position of list cell
* @param progress : new progress value
*/
private fun updateDownloadProgressBar(position :Int, progress:Int)
{
val viewHolder = recyclerViewDownload.findViewHolderForAdapterPosition(position)
(viewHolder as ViewHolderDownload).progressBarDownload.progress=progress
}

关于android - 在 RecyclerView 中更新 ProgressBar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29880257/

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