개요
이 튜토리얼에서는 Android에서 액티비티가 시작되기 전에 진행률 다이얼로그(ProgressDialog)를 화면에 표시하는 방법을 알아봅니다. 데이터 로딩 등 시간이 걸리는 작업을 수행할 때 사용자에게 진행 상태를 알려주는 것은 좋은 사용자 경험(UX)을 제공하는 데 매우 중요합니다.
참고: ProgressDialog는 API 레벨 26(Android 8.0)부터 공식적으로 지원 중단(deprecated)되었습니다. 실제 프로덕션 앱에서는 ProgressBar 위젯이나 DialogFragment를 사용하는 것이 권장되지만, 개념 학습을 위해 이 예제는 여전히 유용하게 활용할 수 있습니다.
1단계: 새 프로젝트 생성
Android Studio를 열고 File ⇒ New Project 메뉴로 이동한 후, 필요한 모든 세부 정보를 입력하여 새 프로젝트를 생성합니다.
2단계: 레이아웃 파일 작성
다음 코드를 res/layout/activity_main.xml 파일에 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="4dp"
tools:context=".MainActivity">
<TextView
android:layout_marginTop="30dp"
android:text="Showing Progress dialog before starting the activity in Android.."
android:textStyle="bold"
android:textSize="24sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>위 레이아웃은 세로 방향의 LinearLayout 안에 안내 문구를 보여주는 TextView 하나를 배치한 간단한 구조입니다.
3단계: MainActivity.java 작성
다음 코드를 src/MainActivity.java 파일에 추가합니다.
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Content Loader");
progressDialog.setProgress(10);
progressDialog.setMax(100);
progressDialog.setMessage("Loading...");
new MyTask().execute();
}
public class MyTask extends AsyncTask<Void, Void, Void> {
public void onPreExecute() {
progressDialog.show();
}
public Void doInBackground(Void... unused) {
return null;
}
}
}핵심 동작 방식은 다음과 같습니다. onCreate() 메서드에서 ProgressDialog 객체를 생성하고 제목, 최대값, 현재 진행률, 메시지를 설정합니다. 그런 다음 AsyncTask를 실행하면 백그라운드 작업이 시작되기 전에 호출되는 onPreExecute()에서 progressDialog.show()를 통해 다이얼로그가 화면에 표시됩니다.
4단계: AndroidManifest.xml 설정
다음 코드를 androidManifest.xml 파일에 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 앱을 실행하려면 프로젝트의 액티비티 파일 중 하나를 연 후 툴바에서 Run 아이콘을 클릭하세요. 옵션으로 모바일 기기를 선택하면, 연결된 기기의 기본 화면에 아래와 같은 결과가 표시됩니다.
