【发布时间】:2023-04-05 11:06:01
【问题描述】:
我有一个显示 Cardviews 的 RecyclerView。每个 CardView 有五 (5) 个 textView。根据每张卡片的类型,我将文本的颜色更改为红色、蓝色或绿色(默认)。所有这些都发生在我的 onBindViewHolder 中,因此性能对我的用户体验至关重要。这是我现在在我的 onBindViewHolder 中所做的。
//set text color per card type
int int_textColor;
String type = arrayListFiltered.get(position).getType().toLowerCase();
String s_rating_type;
if (!FormatFactory.isStringEmpty(type)){
if (type.contains("featured")){
int_textColor = R.color.red;
}else if (type.contains("connector")){
int_textColor = R.color.blue;
}else{
int_textColor = R.color.green;
}
}else{
int_textColor =R.color.green;
}
setTextColor(recyclerViewHolder.tv_rating_type, int_textColor);
setTextColor(recyclerViewHolder.tv_length, int_textColor);
setTextColor(recyclerViewHolder.tv_name, int_textColor);
setTextColor(recyclerViewHolder.tv_location, int_textColor);
setTextColor(recyclerViewHolder.tv_summary, int_textColor);
这是我的 setTextColor 方法
private void setTextColor(TextView tv, int color){
tv.setTextColor(ContextCompat.getColor(tv.getContext(), color));
}
存在许多改变文本颜色的方法,我一直无法找到任何关于提供最佳性能的方法的讨论。即使这段代码工作得很好,我还是会重写它以获得一点性能提升。
【问题讨论】:
-
您在仅在低端设备或全部设备上使用此代码时是否发现任何延迟或性能不佳?
-
我建议如果你想重构它,将
int_textColor作为一个变量存储在你的模型中。这样,您在内存中使用了 5 个额外的int以节省大约 3 * 5 的 if-else 检查。如果您的模型数量或TextView增加,差距会更大