2014-09-28 96 views
4

在文檔中寫明,CardView的BackgroundColor可以使用card_view:cardBackgroundColor以XML格式設置。但是,我無法找到相應的方法來動態更改背景。使用mCardView.setBackgroundColor(Color.argb(75, 102,80,67));將導致CardView失去圓角和陰影。動態更改CardView的BackgroundColor

回答

6

爲cardview的子類提供背景顏色將留下填充的部分,以防卡片視圖中有任何顏色,這不是一種好的方法。

假設您有一個適配器加載卡片視圖中的列表,動態更改卡片視圖的顏色如下。

在適配器的構造Viewholder類

mCardView = (CardView) itemView.findViewById(R.id.card_view); 

在適配器類的onBindViewHolder方法:

holder.mCardView.setCardBackgroundColor(Color.GREEN); // will change the background color of the card view to green 

如果持有人是你的viewholder類的對象。

1

我得到它通過設置CardView的孩子的背景很好地工作:

<android.support.v7.widget.CardView 
     android:id="@+id/card_view" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content"> 
     <LinearLayout 
      android:orientation="vertical" 
      android:id="@+id/card_layout" 
      android:layout_width="match_parent" 
      android:layout_height="72dp"/> 
    </android.support.v7.widget.CardView> 

然後

View cardLayout = mCardView.findViewById(R.id.card_layout); 
    cardLayout.setBackgroundColor(Color.GREEN); 
+0

感謝它按預期工作。 – paradite 2014-10-16 09:29:47

+2

只要cardview具有cardCornerRadius,它就無法按預期工作。仍在尋找更好的解決方案。 – manutudescends 2014-10-24 11:36:16

+0

@manutudescends你確定嗎?它適用於我,我在我的xml中使用了'card_view:cardCornerRadius =「2dp」' – paradite 2014-10-24 18:32:42

-2

有將在即將發佈的API。目前,您唯一的選擇是使用XML。

+0

有沒有這方面的來源? – InsanityOnABun 2014-11-10 02:44:07

+0

請在API發佈時添加此解決方案。 – dasar 2014-12-12 13:26:49