activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<SeekBar
android:id="@+id/pb1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<SeekBar
android:id="@+id/pb2"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="스레드 시작"/>
</LinearLayout>
MainActivity.java
package com.example.thread;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
ProgressBar pb1,pb2;
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pb1 = (ProgressBar) findViewById(R.id.pb1);
pb2 = (ProgressBar) findViewById(R.id.pb2);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(){
public void run(){
for(int i=pb1.getProgress();i<100;i+=2){
pb1.setProgress(pb1.getProgress()+2);
SystemClock.sleep(100);
}
}
}.start();
new Thread(){
public void run(){
for(int i=pb2.getProgress();i<100;i++){
pb2.setProgress(pb2.getProgress()+1);
SystemClock.sleep(100);
}
}
}.start();
}
});
}
}
배운 점
thread를 사용하면 변수값이 바뀔 때마다 바로 화면을 업데이트 해줘서 좀 더 동적인 UI를 구현 할 수 있다. 앱을 만들기 위해서는 필수로 알아두어야 한다.
실행 화면
'안드로이드 > 연습' 카테고리의 다른 글
[Android] ProgressBar&SeekBar (0) | 2021.08.29 |
---|---|
[Android] 간단 MP3 플레이어 만들기 (0) | 2021.08.29 |
[Android] 가수 그룹 관리 DB 만들기 (0) | 2021.08.29 |
[Android] 영화 포스터 보기(GridLayout) (0) | 2021.08.27 |
[Android] ListView (0) | 2021.08.27 |