如何在不锁定UI的情况下初始化RecyclerView适配器? 我要做的就是在创建适配器视图时显示进度条,完成该操作后,隐藏进度条并显示完整的recyclerview适配器。
问题是当我.setAdapter()时,UI冻结了片刻,并且进度栏在那一刻被冻结了。
由于必须在UI线程中完成与视图相关的操作,因此我无法解决该问题。
有什么想法吗?
代码: 从数据库加载数据:
dataLoader = Observable
.just(getApplication().getDbHelper())
.map(this::doInBackground)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::onPostExecute);
onPostExecute方法:
entriesAdapter = new EntriesAdapter(getApplication(), loadedData.entries);
this.loadedData = loadedData;
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
viewHolder.entries.setHasFixedSize(true);
viewHolder.entries.setLayoutManager(layoutManager);
viewHolder.entries.setItemAnimator(new DefaultItemAnimator());
viewHolder.entries.setAdapter(entriesAdapter);
适配器代码:
public class EntriesAdapter extends RecyclerView.Adapter<EntriesAdapter.ViewHolder> {
private BudgeterApplication app;
private List<Expense> entries;
private CompositeDisposable compositeDisposable;
public EntriesAdapter(BudgeterApplication app, List<Expense> entries) {
this.app = app;
this.entries = entries;
}
public void setEntries(List<Expense> entries) {
this.entries = entries;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
return new ViewHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.expense_list_row, viewGroup, false));
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
Expense expense = entries.get(i);
viewHolder.getSumText().setText(BigDecimalUtils.convertToCurrencyString(expense.getSum()));
viewHolder.getCommentText().setText(expense.getComment() == null ? "" : expense.getComment());
viewHolder.getDateText().setText(DateUtils.convertToString(expense.getTimeStamp(), "MM-dd HH:mm"));
}
@Override
public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
compositeDisposable = new CompositeDisposable();
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
if (compositeDisposable != null && !compositeDisposable.isDisposed()) {
compositeDisposable.dispose();
}
super.onDetachedFromRecyclerView(recyclerView);
}
@Override
public int getItemCount() {
return entries.size();
}
@Getter
class ViewHolder extends RecyclerView.ViewHolder {
private View parent;
private TextView sumText;
private TextView commentText;
private TextView dateText;
ViewHolder(@NonNull View itemView) {
super(itemView);
this.parent = itemView;
init();
}
private void init() {
sumText = parent.findViewById(R.id.sum_text);
commentText = parent.findViewById(R.id.comment_text);
dateText = parent.findViewById(R.id.date_text);
}
}
}
答案 0 :(得分:0)
在构造RecycerView项目时,您似乎进行了过多的处理。
此外,请确保设置回收者视图recyclerView.setHasFixedSize(true)
如果这没有帮助,我建议在这里https://developer.android.com/guide/topics/ui/layout/recyclerview
看看最简单的例子这可以很好地工作,因此您可以将其与您的代码进行比较