Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 WebView에서 URL 로딩 시 진행 상태(ProgressBar) 표시하는 방법

이 글에서는 안드로이드 앱에서 WebView가 URL을 로드하는 동안 ProgressBar를 활용해 로딩 진행 상태를 화면에 표시하는 방법을 단계별로 살펴봅니다.

1단계 – 새 프로젝트 생성

Android Studio를 실행한 뒤 File → New Project 메뉴로 이동하고, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력해 새 프로젝트를 만듭니다.

2단계 – 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 중앙에는 로딩 상태를 보여줄 ProgressBar를 배치하고, 그 아래에 전체 화면을 채우는 WebView를 배치합니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:padding="2dp"
    tools:context=".MainActivity">
    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerInParent="true"
        android:max="3"
        android:progress="100" />
    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/progressBar"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="5dp" />
</RelativeLayout>

3단계 – MainActivity 작성

src/MainActivity.kt 파일에 다음 코드를 추가합니다. WebViewClient의 onPageFinished() 콜백에서 페이지 로딩이 완료되면 ProgressBar를 숨기도록 처리하는 것이 핵심입니다.

import android.os.Bundle
import android.view.View
import android.webkit.WebView
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    lateinit var webView: WebView
    lateinit var progressBar: ProgressBar

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        webView = findViewById(R.id.webView)
        progressBar = findViewById(R.id.progressBar)
        webView.webViewClient = WebViewClient()
        webView.loadUrl("https://www.amazon.com")
    }

    inner class WebViewClient : android.webkit.WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            view.loadUrl(url)
            return false
        }

        override fun onPageFinished(view: WebView, url: String) {
            super.onPageFinished(view, url)
            progressBar.visibility = View.GONE
        }
    }
}

4단계 – 매니페스트 설정

androidManifest.xml 파일에 아래 코드를 추가합니다. 외부 웹 페이지를 불러오려면 반드시 INTERNET 권한을 선언해야 한다는 점에 유의하세요.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.q11">
<uses-permission android:name="android.permission.INTERNET"/>
    <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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 후 툴바의 Run(실행) 아이콘을 클릭하면, 연결된 기기에 앱이 설치되고 실행됩니다.

안드로이드 WebView에서 URL 로딩 시 진행 상태(ProgressBar) 표시하는 방법

안드로이드 WebView에서 URL 로딩 시 진행 상태(ProgressBar) 표시하는 방법