1

每個按鈕都代表可點擊的東西,它具有存儲在用戶可配置的數據庫中的顏色。該按鈕的背景是後面的<shape>如何動態更改可繪製的<shape>的顏色? (Android)

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="rectangle"> 
    <stroke android:width="1dp" android:color="#000" /> 
    <corners android:radius="5dp" /> 
    <gradient android:startColor="#FFF" 
      android:centerColor="#FFF" 
      android:endColor="#666" 
      android:angle="315" /> 
    <padding android:bottom="2dp" 
      android:left="2dp" 
      android:right="2dp" 
      android:top="2dp" /> 
</shape> 

我想獲得在<gradient>元素 - 特別是startColorcenterColorendColor屬性。我可以這樣做:

button.getBackground().setTint(theColor); 

但是,這似乎是消除了中風和漸變。

這可能嗎?有沒有更好的辦法?

+0

你試過這種方式嗎?(((GradientDrawable)button.getBackground()).setColor(theColor);' – Ironman

回答

2

嘗試下面片斷,試試看

Have a look at this screenshot

GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, new int[]{ContextCompat.getColor(this,R.color.white), ContextCompat.getColor(this,R.color.red_500), ContextCompat.getColor(this,R.color.blue_500)}); 
    gd.setShape(GradientDrawable.RECTANGLE); 
    gd.setStroke(1, ContextCompat.getColor(this, R.color.black)); 
    gd.setCornerRadius(5f); 
    gd.setBounds(2, 2, 2, 2); 
    findViewById(R.id.btn_analytics).setBackground(gd); 
+0

所以基本上只是重建XML。在這種情況下,我應該徹底廢除XML,而不是重複邏輯。但這種方法很有效,所以我可能會用它。但是必要的改變是將像素值乘以密度。 http://stackoverflow.com/questions/4605527/converting-pixels-to-dp謝謝! –

+0

是的,你不需要再使用xml – Bhavnik

1

請檢查該

GradientDrawable bgShape = (GradientDrawable)button.getBackground(); 
bgShape.setColor(Color.BLACK); 
0

由於以前的答案已經指出的那樣,這是一個GradientDrawable事實證明它, ,有一個花式setColors方法,允許按順序直接訪問這三個xml屬性。但必須通過調用前面到mutate像這樣:

GradientDrawable gd = ((GradientDrawable) button.getBackground()); 
gd.mutate(); 
gd.setColors(new int[]{dynamicColor, 
    ContextCompat.getColor(context, R.color.button), 
    ContextCompat.getColor(context, R.color.button_shade)}); 

@Bhavnik讓我半路上,這樣的感謝。

相關問題