안드로이드 타이머(Android Timer) 예제입니다.


MainActivity

package com.example.호박이_타이머;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
 
public class MainActivity extends Activity {
    int val=0;
    TextView tv01;
    Handler handler;
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv01=(TextView)findViewById(R.id.tv01);
 
        handler = new Handler() {
            public void handleMessage(Message msg) {
                val++;
                tv01.setText("타이머 = " + val);
                if (val <= 9 ) {
                    handler.sendEmptyMessageDelayed(0,1000); // 1초에 1씩 증가(1000 = 1 초)
                }
            }
        };
        handler.sendEmptyMessage(0);
    }
}



activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">
    <TextView android:id="@+id/tv01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerhorizontal="true" android:layout_centervertical="true" android:text="1" android:textsize="30dip">
</TextView></RelativeLayout>



실행 화면

Posted by 준콩ol 준콩ol

댓글을 달아 주세요