2016-09-21 69 views

回答

0

这可能是因为您在RecyclerViewAdapter中正在使用SwappingHolder。此课程不会正确设置CardView的背景颜色。

相反延伸MultiSelectorBindingHolder并覆盖抽象方法,如以下:

class ViewHolder extends MultiSelectorBindingHolder implements View.OnClickListener, 
     View.OnLongClickListener { 
    final CardView cardView; 

    private ColorStateList defaultCardBackground; 
    private ColorStateList selectableCardBackground; 
    private StateListAnimator defaultStateListAnimator; 
    private StateListAnimator selectableStateListAnimator; 
    private boolean selectable; 

    ViewHolder(View view) { 
     super(view, multiSelector); 
     if (view instanceof CardView) { 
      Log.d(TAG, "ViewHolder: got the cardView"); 
      cardView = (CardView) view; 
     } else { 
      throw new IllegalStateException("Expected a CardView!"); 
     } 
     this.selectable = false; 

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
      defaultStateListAnimator = itemView.getStateListAnimator(); 
      selectableStateListAnimator = Utils.getRaiseStateListAnimator(context); 
     } else { 
      defaultStateListAnimator = null; 
      selectableStateListAnimator = null; 
     } 
     defaultCardBackground = cardView.getCardBackgroundColor(); 
     selectableCardBackground = Utils.getSelectableCardBackground(context); 
    } 

    @Override 
    public void setSelectable(boolean selectable) { 
     boolean changed = (selectable != this.selectable); 
     if (changed) { 
      Log.d(TAG, "setSelectable: changed"); 
      this.selectable = selectable; 
      refreshChrome(); 
     } 
    } 

    private void refreshChrome() { 
     Log.d(TAG, "refreshChrome : selectable = " + selectable + ", title:" + download.getTitle()); 

     ColorStateList cardBackgroundColor = this.selectable ? 
       this.selectableCardBackground :this.defaultCardBackground; 
     this.cardView.setCardBackgroundColor(cardBackgroundColor); 

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
      StateListAnimator animator = this.isSelectable() ? 
       this.selectableStateListAnimator : this.defaultStateListAnimator; 
      this.cardView.setStateListAnimator(animator); 
      if(animator != null) { 
       animator.jumpToCurrentState(); 
      } 
     } 
    } 

    @Override 
    public boolean isSelectable() { 
     return selectable; 
    } 

    @Override 
    public void setActivated(boolean b) { 
     cardView.setActivated(b); 
    } 

    @Override 
    public boolean isActivated() { 
     return cardView.isActivated(); 
    } 
}