2016-03-08 73 views
1

我已經定義了一堆繪項目(圖標)與此類似(從谷歌的開源材料圖標):如何在Android中以XML定義形狀外部設置顏色?

<vector xmlns:android="http://schemas.android.com/apk/res/android" 
     android:width="24dp" 
     android:height="24dp" 
     android:viewportWidth="24.0" 
     android:viewportHeight="24.0"> 
    <path 
     android:fillColor="#FF000000" 
     android:pathData="M20,4H4c-1.11,0 -1.99,0.89 -1.99,2L2,18c0,1.11 0.89,2 2,2h16c1.11,0 2,-0.89 2,-2V6c0,-1.11 -0.89,-2 -2,-2zm0,14H4v-6h16v6zm0,-10H4V6h16v2z"/> 
</vector> 

我需要通過造型來改變顏色。它在代碼中使用如下:

  <ImageView 
       android:layout_gravity="center" 
       android:layout_height="wrap_content" 
       android:layout_width="wrap_content" 
       android:layout_weight="1" 
       android:contentDescription="@string/cd.icon_amount" 
       android:src="@drawable/ic_local_atm_24dp"/> 

但是,如何通過外部樣式文件更改ImageView中的顏色?

例如,如何應用下面的XML片段?

<style name="icon"> 
    <item name="color">@color/grey</item> 
</style> 

更新1:我想通過外部文件中的樣式部分更改XML中的顏色,而不是形狀文件。我不希望它以編程方式完成。

回答

0

這個答案是從here

ImageView b = new ImageView(new ContextThemeWrapper(this, R.style.ButtonText), null, 0); 

使用ContextThemeWrapper

使用3-參數的構造函數(沒有這將無法工作)

+0

對不起,如果它是不明確的,但我想它的樣式在XML中,而不是在實際的形狀文件本身。謝謝你的幫助。 – noobsy

0

如果你想以編程方式執行此操作,您可以執行此操作:

首先添加一個ID,你ImageView如下:

<ImageView 
      android:layout_gravity="center" 
      android:layout_height="wrap_content" 
      android:layout_width="wrap_content" 
      android:layout_weight="1" 
      android:id="@+id/ivTest" 
      android:contentDescription="@string/cd.icon_amount" 
      android:src="@drawable/ic_local_atm_24dp"/> 

然後按照這些步驟:

ImageView iv = (ImageView)findViewById(R.id.ivTest); 
GradientDrawable bgShape = (GradientDrawable)iv.getDrawable(); 
bgShape.setColor(ContextCompat.getColor(this, R.color.color)); 
+0

對不起,如果不清楚,但我想用XML格式化它,而不是在實際的形狀文件本身。謝謝你的幫助。 – noobsy

+0

所以你的意思是從XML與ImageView改變形狀的顏色? –

+0

這樣的事情是的。基本上我希望能夠在以後更改樣式文件中的顏色而無需編輯形狀文件。 – noobsy

相關問題