작업스레드 작업스레드에서 현재 시간을 표시하는 예


1. 레이아웃


<?xml version="1.0" encoding="utf-8"?>
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.progdv.currenttime.MainActivity">

<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/linearLayout">

<Button
android:id="@+id/btnStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="시작"
/>

<Button
android:id="@+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="중지"
/>

</LinearLayout>

<TextView
android:id="@+id/txtTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="현재 시간"
android:layout_below="@+id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_margin="25sp"/>

</RelativeLayout>




2. 메인 액티비티


package com.progdv.currenttime;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Date;

public class MainActivity extends AppCompatActivity {

boolean flag = true;
TextView txtTime;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button btnStart = (Button)findViewById(R.id.btnStart);
Button btnStop = (Button)findViewById(R.id.btnStop);
TextView txtTime = (TextView)findViewById(R.id.txtTime);

btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while(flag) {
try {
Date date = new Date();
String currentTime = "현재 시간은: "+date.toString();
// txtTime.setText(currentTime); // 스레드 실행중 UI 변경시 정지된다.
Log.i("MyLog",currentTime);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();

}
}

}
});

thread.start();
}
});

btnStop.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
flag = false;
}
}
}





Posted by netyhobby
,