Android에서 Thread를 이용한 애니메이션(Animation) 예
Activity.onCreate() 안에서..........
airship = (ImageView) findViewById(R.id.airship);
//User Thread 안에서 UI 를 변경할 수 없으며 Handler를 사용해야 한다.
// Handler는 생성만 해주면 자동으로 등록이 되고, User Thread에서 메시지를 전송하면 handleMessage()가 실행된다.
handler = new Handler(){
public void handleMessage(android.os.Message msg) {
AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(140,70,x,y);
airship.setLayoutParams(params);
}
};
animateAirship();
// onCreate() 끝
Activity.onCreate() 안에서..........
airship = (ImageView) findViewById(R.id.airship);
//User Thread 안에서 UI 를 변경할 수 없으며 Handler를 사용해야 한다.
// Handler는 생성만 해주면 자동으로 등록이 되고, User Thread에서 메시지를 전송하면 handleMessage()가 실행된다.
handler = new Handler(){
public void handleMessage(android.os.Message msg) {
AbsoluteLayout.LayoutParams params = new AbsoluteLayout.LayoutParams(140,70,x,y);
airship.setLayoutParams(params);
}
};
animateAirship();
// onCreate() 끝
private void animateAirship(){
airshipStop = false;
new Thread(){
@Override
public void run(){
while(!airshipStop){
if(toRight){
x++;
if(x>=w-airship.getWidth()) toRight=false;
}
else {
x--;
if(x<=0)toRight=true;
}
if(down){
y++;
if(y>=100) down=false;
}else{
y--;
if(y<=0)down=true;
}
handler.sendEmptyMessage(0);
try{
Thread.sleep(100);
}catch(InterruptedException ie){}
}
}
}.start();
}
airshipStop = false;
new Thread(){
@Override
public void run(){
while(!airshipStop){
if(toRight){
x++;
if(x>=w-airship.getWidth()) toRight=false;
}
else {
x--;
if(x<=0)toRight=true;
}
if(down){
y++;
if(y>=100) down=false;
}else{
y--;
if(y<=0)down=true;
}
handler.sendEmptyMessage(0);
try{
Thread.sleep(100);
}catch(InterruptedException ie){}
}
}
}.start();
}