83

보기의 모서리를 둥글게하고 런타임에 내용을 기반으로보기의 색을 변경하고 싶습니다.프로그래밍 방식으로 모서리를 둥글게하고 임의의 배경색을 설정하는 방법

TextView v = new TextView(context); 
v.setText(tagsList.get(i)); 
if(i%2 == 0){ 
    v.setBackgroundColor(Color.RED); 
}else{ 
    v.setBackgroundColor(Color.BLUE); 
} 

v.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); 
v.setPadding(twoDP, twoDP, twoDP, twoDP);    
v.setBackgroundResource(R.drawable.tags_rounded_corners); 

드로어 블을 설정하고 색상이 겹치기를 바랬지 만 그럴 수는 없습니다. 어느 것이 든 내가 두 번째로 실행하는 것은 결과적인 배경이다.

런타임까지 배경색이 결정되지 않는다는 것을 염두에두고 프로그래밍 방식으로이보기를 만들 수 있습니까?

편집 : 이제 테스트를 위해 빨강과 파랑 사이를 바꿀뿐입니다. 나중에 사용자가 색상을 선택할 수있게됩니다.

편집 :

tags_rounded_corners.xml 대신 setBackgroundColor

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" > 
    <corners 
     android:bottomRightRadius="2dp" 
     android:bottomLeftRadius="2dp" 
     android:topLeftRadius="2dp" 
     android:topRightRadius="2dp"/> 
</shape> 
+0

물론 배경색과 배경 이미지가 서로 대체됩니다. 무엇을 성취하려고합니까? 'tags_rounded_corners'는 무엇입니까? –

+0

더 많은 코드를 보여줄 수 있습니까? 그것은 괜찮아 보이는 그래서 당신이 listView 종류를 사용하거나 기존 textview 재사용 할 수도 있습니다. – Chansuk

+0

확인해보십시오. http://www.gadgetsaint.com/tips/rounded-corners-views-layouts-android/#.WPZ2QVN97BI – ASP

답변

148

, 배경 묘화를 검색하고 색 설정 : 당신은 내 패딩을 정의 할 수 있습니다, 또한

v.setBackgroundResource(R.drawable.tags_rounded_corners); 

GradientDrawable drawable = (GradientDrawable) v.getBackground(); 
if (i % 2 == 0) { 
    drawable.setColor(Color.RED); 
} else { 
    drawable.setColor(Color.BLUE); 
} 

당신의 tags_rounded_corners.xml :

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <corners android:radius="4dp" /> 
    <padding 
    android:top="2dp" 
    android:left="2dp" 
    android:bottom="2dp" 
    android:right="2dp" /> 
</shape> 
+0

예문과 답! 그것은 또한 잘 작동하지만, 우리는 같은 것을 사용하여이 작업을 수행 할 수 있습니다. colorDrawable = resources.getDrawable (R.drawable.x_sd_circle); colorDrawable.setColorFilter (color, PorterDuff.Mode.SRC_ATOP); 국경이없는 경우. 국경의 경우 획 색상이 변경되지 않도록 PorterDuff.Mode를 알려 주시기 바랍니다 –

+0

XML을 통해 배경색을 추가하는 방법은 무엇입니까? – emaillenin

+2

"v"가 v.getBackground()보다 TextView 인 경우 "java.lang.ClassCastException : android.graphics.drawable.StateListDrawable을 android.graphics.drawable.GradientDrawable에 캐스팅 할 수 없습니다." ? – sonavolob

86

둥근 모서리를 설정하고 임의의 배경색을보기에 추가하는 프로그래밍 방식의 총계입니다. 코드를 테스트하지 않았지만 아이디어를 얻었습니다. ShapeDrawable는 그러한 방법을 제공하지 않기 때문에 우리가 GradientDrawable#setCornerRadius의 사용을 할 수 있도록

GradientDrawable shape = new GradientDrawable(); 
shape.setCornerRadius(8); 

// add some color 
// You can add your random color generator here 
// and set color 
if (i % 2 == 0) { 
    shape.setColor(Color.RED); 
} else { 
    shape.setColor(Color.BLUE); 
} 

// now find your view and add background to it 
View view = (LinearLayout) findViewById(R.id.my_view); 
view.setBackground(shape); 

는 여기에서 우리는 그라데이션 당김을 사용하고 있습니다. 당신이 뇌졸중하지 않는 경우

+11

shape.setCornerRadii (corner); 그 매우 유용한 – umesh

+0

슈퍼 대답 @ jayadeepw –

+7

'GradientDrawable' 대신'PaintDrawable'을 사용하는 것을 고려하십시오. 둥근 모서리와 그라디언트보다 더 적합한 단일 색상을 지원합니다. – Cimlman

2

당신이

colorDrawable = resources.getDrawable(R.drawable.x_sd_circle); 

colorDrawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP); 

를 사용할 수 있지만이 또한 획 색상을

+23

나는 이것을 사용하려고했으나 뇌졸중이 있습니다. –

7

변경됩니다 나는이 작업을 수행하는 가장 빠른 방법이라고 생각 :

GradientDrawable gradientDrawable = new GradientDrawable(
      GradientDrawable.Orientation.TOP_BOTTOM, //set a gradient direction 
      new int[] {0xFF757775,0xFF151515}); //set the color of gradient 
gradientDrawable.setCornerRadius(10f); //set corner radius 

//Apply background to your view 
View view = (RelativeLayout) findViewById(R.id.my_view); 
if(Build.VERSION.SDK_INT>=16) 
    view.setBackground(gradientDrawable); 
else view.setBackgroundDrawable(gradientDrawable);  
0

당신에게 이 같은 DrawableCompat을 사용하여 더 잘 달성 할 수 있습니다.

Drawable backgroundDrawable = view.getBackground();    
DrawableCompat.setTint(backgroundDrawable, newColor); 
관련 문제