1

각 버튼은 사용자가 구성 할 수있는 데이터베이스에 저장된 색상이있는 클릭 가능한 것을 나타냅니다. 단추의 배경은 다음에 나오는 <shape>입니다.드로어 블의 색상을 어떻게 동적으로 변경합니까 <shape>? (안드로이드)

<?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 메소드를 가지고 있으며,이 3 개의 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가, 중간이 저를 얻었다 감사 때문에.