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

안드로이드 WebView 구현 완벽 가이드: 단계별 예제 코드

WebView 구현에 들어가기 앞서, WebView가 무엇인지 먼저 이해할 필요가 있습니다. WebView는 안드로이드 View 클래스를 확장(extend)한 컴포넌트로, 앱 내부에서 HTML 콘텐츠나 웹 페이지를 표시하는 데 사용됩니다.

WebView에서 제공하는 주요 메서드

  • clearHistory() — WebView의 방문 기록을 삭제합니다.

  • destroy() — WebView의 내부 상태를 파괴하고 리소스를 정리합니다.

  • getUrl() — 현재 WebView에 로드된 URL을 반환합니다.

  • getTitle() — 현재 WebView의 페이지 제목을 반환합니다.

  • canGoBack() — 현재 WebView에 뒤로 갈 수 있는 히스토리 항목이 있는지 여부를 나타냅니다.

기본 설정 그대로 사용하면 WebView는 콘텐츠를 열 때 기본 안드로이드 브라우저를 실행합니다. 만약 외부 브라우저가 아닌 애플리케이션 내부에서 페이지를 열고 싶다면, 아래와 같이 shouldOverrideUrlLoading을 오버라이드하여 false를 반환하도록 처리해야 합니다.

private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url) {
        return false;
    }
}

이제 실제 예제를 통해 안드로이드에서 WebView를 구현하는 방법을 단계별로 살펴보겠습니다.

1단계 — 새 프로젝트 생성

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

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

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout
    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">
    <WebView
        android:layout_width = "match_parent"
        android:layout_height = "match_parent"
        android:id = "@+id/webView" />
</android.support.constraint.ConstraintLayout>

3단계 — MainActivity 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import timber.log.Timber;
public class MainActivity extends AppCompatActivity {
    private WebView simpleWebView;
    private ProgressBar loadProgress;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        simpleWebView=findViewById(R.id.webView);
        simpleWebView.setWebViewClient(new WebViewClient());
        simpleWebView.getSettings().setLoadsImagesAutomatically(true);
        simpleWebView.getSettings().setJavaScriptEnabled(true);
        simpleWebView.setScrollBarStyle(View.VISIBLE);
        simpleWebView.getSettings().setBuiltInZoomControls(true);
        simpleWebView.getSettings().setSupportZoom(true);
        simpleWebView.getSettings().setLoadWithOverviewMode(true);
        simpleWebView.getSettings().setUseWideViewPort(true);
        simpleWebView.getSettings().setAllowContentAccess(true);
        simpleWebView.loadUrl("https://www.tutorialspoint.com/");
    }
    @Override
    public void onBackPressed() {
        if (simpleWebView.canGoBack()) {
            simpleWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }
}

위 코드에서 loadUrl() 부분에는 본인이 원하는 웹사이트 주소를 입력하면 됩니다. 또한 onBackPressed()를 오버라이드하여, 뒤로 갈 히스토리가 남아 있으면 앱을 종료하지 않고 이전 페이지로 이동하도록 처리했습니다.

4단계 — AndroidManifest.xml 수정

AndroidManifest.xml 파일에 아래 코드를 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
    package = "com.example.andy.myapplication">
<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.permission.INTERNET)을 선언한 이유는, 인터넷상의 웹사이트를 호출하기 때문입니다. 이 권한이 없으면 WebView가 네트워크에 접근할 수 없어 페이지가 로드되지 않습니다.

5단계 — strings.xml 작성

res/values/string.xml 파일에 아래 코드를 추가합니다.

<resources>
    <string name = "app_name">My Application</string>
    <string name = "erroopsproblem">Something error</string>
</resources>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 옵션 목록에서 자신의 모바일 기기를 선택하면, 모바일 기기에 기본 화면이 표시됩니다.

안드로이드 WebView 구현 완벽 가이드: 단계별 예제 코드

이제 화면에서 요소를 클릭해 보세요. 예를 들어 위 화면에서 HTML 아이콘을 클릭하면, 아래와 같은 결과가 표시됩니다.

안드로이드 WebView 구현 완벽 가이드: 단계별 예제 코드