마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

버튼 배경을 Drawable로 지정했을 때 색상 변경 방법 문의

0 추천

안녕하세요.

동그라미 버튼을 만드려고 아래와 같이 이미지 버튼을 만들고

<ImageButton
            android:layout_width="56dp"
            android:layout_height="56dp"
            android:background="@drawable/test_round_btn"
            android:src="@drawable/ic_search_white_24dp"/>

 

Selector로 동그랗게 만들었습니다.

# test_round_btn.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false">
        <shape android:shape="oval">
            <solid android:color="#fa09ad"/>
        </shape>
    </item>
    <item android:state_pressed="true">
        <shape android:shape="oval">
            <solid android:color="#c20586"/>
        </shape>
    </item>
</selector>

 

이때, selector에 색상을 다이나믹하게 바꾸고 싶은데..가능한가요?

<solid android:color="#fa09ad"/> 이부분을 코드로 바꾸는 방법이 가능한지...알고싶습니다!

치솟음 (3,710 포인트) 님이 2015년 10월 23일 질문

1개의 답변

0 추천

넵 가능합니다. 

<!-- test_round_shape.xml -->

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

 

{ // 소스코드

  StateListDrawable state = new StateListDrawable();

  state.addState(new int[] { android.R.attr.state_pressed }, GetDrawable(R.drawable.test_round_shape,   Color.Green));
  state.addState(new int[] { -android.R.attr.state_pressed }, GetDrawable(R.drawable.test_round_shape,   Color.Black));

  ImageButton imageButton = (ImageButton) findViewById(R.id.test_image_btn);

  imageButton .setBackgroundDrawable(state); // imageButton .setBackground(state);

}

public Drawable GetDrawable(int drawableResId, int color) {
  Drawable drawable =  getResources().getDrawable(drawableResId);
  drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
  return drawable;
}

이렇게 하시면 소스코드상에서 color를 임의대로 주어 사용 할 수 있습니다. 

위 코드에서는 Color.Green, Color.Black을 사용했는데, 

사용 하고 싶으신 색상 int값을 저기다 바꿔 넣어 주시면 됩니다.

 

 

익명사용자 님이 2015년 10월 23일 답변
...