8/19/2013

안드로이드 타이머 (핸들러 사용)

Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
>
<TextView
   android:id="@+id/text"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:textColor="#ff0000"
   android:textSize="40sp"
   android:text="0"
   />

</LinearLayout>


Code:

public class MainActivity extends Activity
{
int value = 0;
TextView mText;

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mText = (TextView)findViewById(R.id.text);
mHandler.sendEmptyMessage(0);
}

Handler mHandler = new Handler()
{
public void handleMessage(Message msg)
{
value++;
mText.setText("Value = " + value);
mHandler.sendEmptyMessageDelayed(0, 1000);
}
};
}

타이머 처리를 위해 핸들러(스레드 간의 메시지 통신을 위한 장치) 클래스 사용.

Better code:

public class MainActivity extends Activity
{
int value = 0;
TextView mText;
Handler mHandler;

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mText = (TextView)findViewById(R.id.text);

mHandler = new Handler() {
public void handleMessage(Message msg)
{
value++;
mText.setText("Value = " + value);
mHandler.sendEmptyMessageDelayed(0, 1000);

}
};
mHandler.sendEmptyMessage(0);
}
}




출처: 안드로이드 프로그래밍 정복 1권

No comments:

Post a Comment