Thread Animation이란?
애니메이션을 앱에서 구현하려고 한다면 어떤 방식으로 구현해야 할까?
예전 만화에서는 여러 장의 사진을 그리고 이 사진들을 빠르게 바꿔서 마치 사진이 움직이는 것처럼 구현하였다.
안드로이드에서 Thread를 이용하여 ImageView를 계속 바꿔준다면 이와 같이 구현할 수 있을 것이다.
이렇게 Thread를 이용하여 이미지를 바꾸어 표현한 애니메이션을 Thread Animation이라고 한다.
사용법
Resources res = getResources();
ArrayList<Drawable> imageList = new ArrayList<Drawable>();
imageList.add(res.getDrawable(R.drawable.icon1));
imageList.add(res.getDrawable(R.drawable.icon2));
imageList.add(res.getDrawable(R.drawable.icon3));
imageList.add(res.getDrawable(R.drawable.icon4));
imageList.add(res.getDrawable(R.drawable.icon5));
imageList.add(res.getDrawable(R.drawable.icon6));
먼저 바꾸어 줄 이미지를 Drawable 객체로 불러와 ArrayList에 담아주자.
class AnimThread extends Thread {
@Override
public void run() {
for(int i = 1; i<100; i++){
int cur = i % 6;
final Drawable drawable = imageList.get(cur);
handler.post(new Runnable() {
@Override
public void run() {
imageView.setImageDrawable(drawable);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
다음으로 Thread 클래스를 생성하여 애니메이션이 작동하도록 구현해보자.
반복문을 돌면서 1초마다 setImageDrawable() 함수를 통해 이미지를 바꿔주도록 해보자.
※ Thread와 Handler 사용법은 아래 글을 참고.
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AnimThread thread = new AnimThread();
thread.start();
}
});
마지막으로 버튼을 누르면 Thread를 실행하도록 하면 된다.
버튼을 누르면 쓰레드가 실행되어 이미지가 바뀌는 것을 볼 수 있다.
Reference
[부스트코스]안드로이드 프로그래밍
'Android > Concepts' 카테고리의 다른 글
Page Sliding 구현하기 (0) | 2020.05.08 |
---|---|
Animation 사용법 (0) | 2020.05.07 |
RecyclerView 사용법 (0) | 2020.05.04 |
MediaRecorder로 Audio 녹음하기 (2) | 2020.05.04 |
MediaPlayer로 Audio와 Video 파일 재생하기 (0) | 2020.05.03 |