【问题标题】:How to change color of a single item in RecyclerView?如何更改 RecyclerView 中单个项目的颜色?
【发布时间】:2017-03-21 09:40:22
【问题描述】:

我在从资源中为 RecyclerView 中的项目设置颜色时遇到问题。 我已经尝试了这两种方法,但没有一个有效。任何想法我做错了什么?

holder.alert.setTextColor(R.color.alertGreen);
holder.alert.setTextColor(getResources().getColor(R.color.alertGreen));

【问题讨论】:

  • 在此处发布您的项目 xmll 和适配器类
  • setTextColor(Color.parseColor("#54D66A"));

标签: java android android-recyclerview


【解决方案1】:

使用ContextCompat 获取颜色。

holder.alert.setTextColor(ContextCompat.getColor(context, R.color.alertGreen));

【讨论】:

    【解决方案2】:

    要更新单个项目的颜色,您可以遵循以下技术,

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    
    // Green color to set to specific item in the view [By referencing the position you need to handle the view]
    int color1 = ContextCompat.getColor(context, R.color.alertGreen));
    
    // Red color to set to remaining Views
    int color2 = ContextCompat.getColor(context, R.color.alertRed));
    
         if (position == 1) {
           holder.alert.setTextColor(color1);
         } else {
           holder.alert.setTextColor(color2);
         }
    }
    

    【讨论】:

      【解决方案3】:

      你应该使用ContextCompact而不是getResources(),因为这个方法是deprecated。

      holder.alert.setTextColor(ContextCompat.getColor(context, R.color.red));
      

      【讨论】:

        【解决方案4】:

        在onBindViewHolder(RecyclerView.ViewHolder holder, int position)方法中你可以改变当前元素的颜色:

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            holder.alert.setTextColor(R.color.alertGreen);
            holder.alert.setTextColor(getResources().getColor(R.color.alertGreen);
        }
        

        并使用ContextCompat 获取颜色:

        ContextCompat.getColor(context, R.color.alertGreen));
        

        【讨论】:

          【解决方案5】:

          使用 ContextCompat 的另一种方法是:

          holder.alert.setTextColor(context.getResources().getColor(R.color.alertGreen));
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-06-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-28
            • 2016-05-08
            • 1970-01-01
            相关资源
            最近更新 更多