Android开发:使用RecyclerView.Adapter时如何访问Fragment中的colorList数组
解决方法
1. 修正InboxAdapter代码
你当前的Adapter存在两个问题:构造函数未对传入的colorList做赋值、变量名拼写不一致,修正后代码如下:
public class InboxAdapter extends RecyclerView.Adapter<InboxAdapter.ViewHolder> { private static final String LOG_TAG = InboxAdapter.class.getSimpleName(); private boolean reverseAllAnimations = false; private SparseBooleanArray selectedItems; private Context mContext; // 补全缺失的mContext成员声明 public List<inbox> mInboxes; public ArrayList<String> colorList; // 修正构造函数,将传入的colorList赋值给内部成员 public InboxAdapter(Context mContext, List<inbox> inboxes, List<String> colorList) { this.mContext = mContext; mInboxes = inboxes; this.colorList = (ArrayList<String>) colorList; } @Override public void onBindViewHolder(ViewHolder holder, int position) { inbox inbox = mInboxes.get(position); holder.subject.setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.N) @Override public void onClick(View v) { int idx = holder.getAdapterPosition(); // 加边界判断避免下标越界崩溃 if (idx == RecyclerView.NO_POSITION || idx >= colorList.size()) { return; } String id = mInboxes.get(idx).getId(); String color = colorList.get(idx); // 修正变量名,本身为String类型无需额外toString // 其余mailbox、short_name等变量请自行确保可正常取值 openEmailActivity(mailbox, id, color, short_name, subject1, from, from_email, datetime, isImportant); } }); } // 其余原有代码保持不变即可 }
2. 修正InboxFragment初始化逻辑
你原有逻辑顺序错误:还未完成列表渲染就尝试取RecyclerView子View,会导致getChildCount返回0、colorList无数据,同时初始化Adapter时未传入colorList,修正后代码如下:
private void setupRecyclerView(@NonNull RecyclerView recyclerView) { // 先初始化colorList ArrayList<String> colorList = new ArrayList<>(); // 初始化Adapter时传入colorList mInboxAdapter = new InboxAdapter(getActivity(), mInbox, colorList); // 先设置布局管理器和Adapter,触发列表渲染 GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 1); recyclerView.setLayoutManager(layoutManager); recyclerView.setHasFixedSize(true); recyclerView.setAdapter(mInboxAdapter); // 等RecyclerView渲染完成后再提取颜色,保证能拿到子View recyclerView.post(new Runnable() { @Override public void run() { int itemsCount = recyclerView.getChildCount(); int index1 = 0; for (int i = 0; i < itemsCount; i++) { View view = recyclerView.getChildAt(i); GradientDrawable gradientDrawable = (GradientDrawable) view.findViewById(R.id.tvIcon).getBackground(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { int intColor = gradientDrawable.getColor().getDefaultColor(); String hexColor = Integer.toHexString(intColor).substring(2); String colors = "#" + hexColor; colorList.add(index1, colors); index1++; } } // 颜色数据更新后通知Adapter刷新 mInboxAdapter.notifyDataSetChanged(); } }); }
优化建议
如果你的列表项超过一屏,上述通过getChildAt获取可见项的方式只能拿到屏幕显示范围内的条目颜色,更稳定的方案是直接在Adapter的onBindViewHolder中生成对应位置的颜色并存入colorList,无需在Fragment中额外遍历提取。
内容的提问来源于stack exchange,提问作者chris oojer
相关产品推荐
相关产品推荐

