2015-10-04 33 views
0

我有以下XML資源的代碼是卡項目列表的背景佈置更改繪製資源編程

<?xml version="1.0" encoding="utf-8"?> 
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item> 
     <shape android:shape="rectangle"> 
      <solid android:color="#CABBBBBB"/> 
      <corners android:radius="2dp" /> 
     </shape> 
    </item> 

    <item 
     android:left="0dp" 
     android:right="0dp" 
     android:top="0dp" 
     android:bottom="2dp" 
     android:drawable="@drawable/kpop"> 
     <shape android:shape="rectangle"> 
      <solid android:color="#151B54"/> 
      <corners android:radius="2dp" /> 
     </shape> 
    </item> 
</layer-list> 

我的問題是,我想改變繪製資源編程

android:drawable="@drawable/kpop" 

(這樣每個卡片都會有不同的背景圖像)

任何想法/提示我該怎麼做?

回答

2

這裏是你如何能做到這一點:

  1. 獲得一個參考圖層列表

    LayerDrawable layer = (LayerDrawable)yourView.getBackground();

    或者

    LayerDrawable layer = (LayerDrawable)context.getResources().getDrawable(R.id.yourLayerDrawable);

  2. 創建圖層繪製的新實例內部

    layer.Mutate();

    Android的內部緩存繪項目,這意味着,如果通過上述方法修改繪製obtaind,所有其他繪圖資源將受到影響。爲了防止這種情況,您可以撥打Drawable.Mutate()告訴系統保留一個單獨的可繪製副本,以便它不會影響其他可繪製副本。

  3. 設置ID爲項修改

    android:id="@+id/image_background"

像這樣:

<item 
    android:left="0dp" 
    android:right="0dp" 
    android:top="0dp" 
    android:bottom="2dp" 
    android:id="@+id/image_background" <---- 
    android:drawable="@drawable/kpop"> 
    <shape android:shape="rectangle"> 
     <solid android:color="#151B54"/> 
     <corners android:radius="2dp" /> 
    </shape> 
</item> 

  • 設置/重置可繪製該項目

    layer.setDrawableByLayerId(R.id.image_background, yourNewDrawable);

  • 重繪層

    layer.invalidateSelf();

  • +0

    不爲我工作..: '( – Lobato

    +0

    如果確實有效的話會很棒。我花了整整一天,這不能讓它工作:( –

    1

    你沒有發佈你的java代碼..我認爲它可以幫助你。 嘗試在您自己的邏輯中使用此代碼。

    yourCard.setBackgroundDrawable(getResources().getDrawable(R.drawable.kpop));

    yourCard.setBackground(R.drawable.kpop); 
    

    代碼沒有測試,但我認爲這將工作..評論請再多問。