2014-11-22 3 views
1

버튼이있어서 돌고 싶기 때문에 xml 파일을 만들어 배경으로 설정했습니다. 버튼은 이제 둥글지만 xml 파일로 하드 코딩하는 대신 프로그래밍 방식으로 색상을 변경할 수 있기를 원합니다. 어떻게해야합니까?버튼 색상을 프로그래밍 방식으로 변경하는 방법 - Android

여기 내 둥근 버튼을위한 xml 파일입니다.

<?xml version="1.0" encoding="utf-8"?> 
     <shape xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="oval"> 
      <solid android:color="#ffcb05"/> 
     </shape> 

답변

1

이 시도 :

GradientDrawable backgroundShape = (GradientDrawable)btn.getBackground(); 
backgroundShape.setColor(Color.BLACK); 
1

시도가 getPaint 사용하여 버튼 배경 세트 색상을 얻을 :

((ShapeDrawable)yourbutton.getBackground()).getPaint().setColor(getResources().getColor(R.color.colorToSet)); 
9

당신은 ColorFilter를 사용하여보기의 색상을 변경할 수 있습니다. 그것은 매우 쉽고 빠릅니다.

button.getBackground().setColorFilter(Color.RED, PorterDuff.Mode.SRC_ATOP); 

이 코드는 붉은 색으로 버튼을 색칠합니다.

관련 문제