【问题标题】:Recyclerview setting background color programaticallyRecyclerview 以编程方式设置背景颜色
【发布时间】:2021-10-18 05:32:01
【问题描述】:

我正在通过改造从服务器获取数据。如果数据为正,则颜色应为绿色,否则应为红色。就像 Sensex 一样,如果它是阳性的,那么它会显示绿色,否则会显示红色。 See Image for reference.Onbind 视图我在下面完成,但它是用于网格视图中的位置

@Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        if(position % 2 ==0) {
            holder.itemView.setBackgroundColor(
                    ContextCompat.getColor(holder.itemView.getContext(), R.color.red));
        } else {
            holder.itemView.setBackgroundColor(
                    ContextCompat.getColor(holder.itemView.getContext(), R.color.green));
        }

如何实现。

【问题讨论】:

标签: android android-recyclerview retrofit android-cardview


【解决方案1】:
  1. 您可以准备一个单独的列表来显示adapter.like中的数据 - `List<ListItem> listDisplay= new ArrayList()`
  2. 创建提供 getter() 和 setter() 方法的 ListItem 类。 访问https://www.w3schools.com/java/java_encapsulation.asp。您可以创建 一个变量,它是这个类中的 getter() 和 setter() 方法,基于 您在卡片视图上显示数据的要求
  3. 当您将收到来自服务器的列表数据时,创建一个实例 ListItem 类和使用循环只是将接收到的值设置为其 变量并将接收到的数据项添加到列表listDisplay中
  4. 在初始化时将此 listDisplay 传递给 adapter 的构造函数。
  5. 在adapter的onBindViewHolder()方法中,执行如下代码
     position) {
   //create a ListItem
   ListItem listItem = *listMaintainedInAdapter*.get(position)
           
   /*create a instance of adapter's view holder class who holds the 
    views reference.*/
    
   
   /*Check data is positive or not. here, num is variable declared in 
         ListItem class who holds the value which you want to check*/
   
   if(listItem.num > 0){    
         //set card colour to green
   }else{
           //set card colour to red.
   }
}```

【讨论】:

    【解决方案2】:
        @Override
            public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
                val data = list[holder.adapterPosition]
                if (data.changeValue > 0) {
                    holder.itemView.setBackgroundColor(
                            ContextCompat.getColor(holder.itemView.getContext(), R.color.red));
                } else {
                    holder.itemView.setBackgroundColor(
                            ContextCompat.getColor(holder.itemView.getContext(), R.color.green));
                }
        }
    

    data.changeValue 是来自 API 的数据值,例如 207.57 或 -63.85(我只是假设)。我希望这个解决方案能解决您的问题。

    【讨论】:

      猜你喜欢
      • 2014-06-24
      • 2011-01-09
      • 1970-01-01
      • 2023-03-26
      • 2019-04-22
      • 2023-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多