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

안드로이드 WebView에서 URL 로딩 중 진행률 표시줄(프로그레스 바) 구현하는 방법

이 튜토리얼에서는 안드로이드 앱에서 WebView로 웹페이지(URL)를 로드하는 동안 진행률 표시줄(프로그레스 바)을 화면에 표시하고, 로딩이 완료되면 자동으로 숨기는 방법을 단계별로 알아봅니다.

웹페이지 로딩은 네트워크 상태에 따라 몇 초 이상 걸릴 수 있습니다. 이때 로딩 중임을 사용자에게 시각적으로 알려주는 프로그레스 바는 앱의 사용자 경험(UX)을 크게 향상시켜 줍니다.

1단계 — 새 프로젝트 생성

Android Studio에서 새 프로젝트를 생성합니다. 상단 메뉴에서 File ⇒ New Project로 이동한 후, 새 프로젝트 생성에 필요한 모든 세부 정보를 입력합니다.

2단계 — activity_main.xml 레이아웃 작성

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"
    tools:context=".MainActivity">
    <ProgressBar
        android:id="@+id/progressBar"
        android:max="3"
        android:progress="100"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerInParent="true" />
    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/progressBar"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

3단계 — MainActivity.java 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다. 핵심은 커스텀 WebViewClient를 정의하여 onPageFinished() 콜백에서 페이지 로딩이 끝나면 프로그레스 바를 숨기는 것입니다. 또한 shouldOverrideUrlLoading()을 오버라이드하여 링크 클릭 시 외부 브라우저가 아닌 앱 내부 WebView에서 계속 열리도록 처리했습니다.

import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
    WebView webview;
    ProgressBar progressBar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webview = findViewById(R.id.webView);
        progressBar = findViewById(R.id.progressBar);
        webview.setWebViewClient(new WebViewClient());
        webview.loadUrl("https://www.google.com");
    }
    public class WebViewClient extends android.webkit.WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressBar.setVisibility(View.GONE);
        }
    }
}

4단계 — AndroidManifest.xml 설정

androidManifest.xml 파일에 아래 코드를 추가합니다. 특히 <uses-permission android:name="android.permission.INTERNET"/>처럼 인터넷 권한을 반드시 선언해야 합니다. 이 권한이 없으면 WebView가 네트워크에 접근하지 못해 페이지가 로드되지 않습니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <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(실행) 아이콘을 클릭하세요. 옵션 목록에서 본인의 모바일 기기를 선택하면, 기기 화면에 아래와 같이 기본 화면이 표시됩니다.

앱이 시작되면 Google 페이지를 로드하는 동안 화면 중앙에 프로그레스 바가 나타나고, 로딩이 완료되면 자동으로 사라지며 웹페이지가 표시됩니다.

안드로이드 WebView에서 URL 로딩 중 진행률 표시줄(프로그레스 바) 구현하는 방법