본문 바로가기

나의 플랫폼/안드로이드

[Android] Background animation에 쓸만한 TransitionDrawable

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

혹시 RadioButton 이나 Switch 관련된 View를 사용하고자 할 경우, 한번 고려해보면 나쁘지 않을 것이다.

그냥 xml로 정의 해서 background에 넣는 방법이 있고, 직접 코드에 넣을 수도 있다.


1. xml로 정의


res/drawable 폴더안에 btn_transition_drawable.xml 라는 xml 파일을 만들어 놓고, 아래 소스대로 코딩 합니다.

<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/background_drawable1"/>
<item android:drawable="@drawable/background_drawable2"/>
</transition>

그 다음, 사용하고자 하는 View background에 위 xml로 설정 합니다.

<View

android:id="@+id/view_transition_drawable"
android:layout_width="88dp"
android:layout_height="38dp"
android:layout_margin="2dp"
android:background="@drawable/btn_transition_drawable"/>

이로써 설정은 끝났습니다.

이제 TransitionDrawable에 Animation을 동작하게 하는 코드만 넣어주면 됩니다.

코드는 아래와 같습니다.

// set background animation
Drawable drawable = findViewById(R.id.view_transition_drawable).getBackground();

if (drawable != null && drawable instanceof TransitionDrawable) {
    ((TransitionDrawable)drawable).startTransition(300);
}

다시 이전 Drawable로 돌아가고자 할 경우에는 아래 함수를 이용합니다.

((TransitionDrawable)beforeDrawable).resetTransition();

((TransitionDrawable)beforeDrawable).reverseTransition(300);

함수명을 보면 알 수 있듯이 resetTransition은 초기화, reverseTransition은 Animation을 거꾸로 하는 함수 입니다.



2. 코드로 정의


Animation 동작은 위 설명에 포함되어 있으므로, 여기에서는 코드로 TransitionDrawable를 Background로 설정하는 소스 설명하겠습니다.


Drawable[] drawables = {
getDrawable(getActivity()
,R.drawable.background_drawable1),
getDrawable(getActivity(),R.drawable.background_drawable2)
}
;
findViewById(R.id.cast_cell_rippleview_).setBackground(
new TransitionDrawable(drawables)
)
;

위 getDrawable 참고 소스 : http://gogorchg.tistory.com/entry/Android-getDrawable-getColor-deprecated

이렇게 하면 코드로 Background가 TransitionDrawable로 변경이 됩니다.


## 참고 사항

제가 테스트해본 바, TransitionDrawable은 초기 상태가 배열 0 번째가 되지 않습니다.

따라서 미리 한번 아래와 같이 startTransition 함수를 호출 하면 원하시는 동작이 이뤄질꺼라고 생각 되네요 ㅎ


Drawable drawable = findViewById(R.id.view_transition_drawable).getBackground();
if (drawable != null && drawable instanceof TransitionDrawable) {
((TransitionDrawable)drawable).startTransition(0);
}


참고하세요.