【问题标题】:Best performance for setting TextView color programmatically以编程方式设置 TextView 颜色的最佳性能
【发布时间】: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 增加,差距会更大

标签: android colors textview


【解决方案1】:

我认为您可以覆盖适配器的方法getItemViewType,并以不同的颜色填充不同的布局。让适配器处理颜色变化,而不是动态改变颜色。

例如:

public class MyAdapter extends RecyclerView.Adapter<T> {

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        int rid;
        switch (viewType) {
            case 0: // for featured type
                rid= R.layout.red;
                break;
            case 1 : // for connector type
                rid= R.layout.blue;
                break;
            default:
                rid= R.layout.green;
                break;
        }
        View v= LayoutInflater.from(parent.getContext()).inflate(id, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public int getItemViewType(int position) {
        return arrayListFiltered.get(position).getType(); // need int type
    }

    ...
}

【讨论】:

  • 这毫无意义。你为什么要膨胀额外的布局来避免像设置文本颜色这样的廉价操作?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-08
  • 1970-01-01
  • 1970-01-01
  • 2019-03-27
  • 2016-07-03
  • 2011-03-09
  • 1970-01-01
相关资源
最近更新 更多