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

안드로이드 WebView 기본 텍스트 인코딩(UTF-8) 설정 방법

이 튜토리얼에서는 안드로이드 WebView에서 기본 텍스트 인코딩(default text encoding)을 설정하는 방법을 단계별로 알아봅니다. 한글·일어 등 멀티바이트 문자가 포함된 웹 페이지가 깨져 보일 때 setDefaultTextEncodingName() 메서드를 활용하면 손쉽게 문제를 해결할 수 있습니다.

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:app = "https://schemas.android.com/apk/res-auto"
   xmlns:tools = "https://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:orientation = "vertical">
   <WebView
      android:id = "@+id/web_view"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent" />
</LinearLayout>

위 코드는 facebook.com 웹 페이지를 표시하기 위해 WebView를 화면에 배치한 레이아웃입니다.

3단계 — MainActivity 구현

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

package com.example.myapplication;
import android.app.ProgressDialog;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
    @RequiresApi(api = Build.VERSION_CODES.P)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading Data...");
        progressDialog.setCancelable(false);
        WebView web_view = findViewById(R.id.web_view);
        web_view.requestFocus();
        web_view.getSettings().setDefaultTextEncodingName("utf-8");
        web_view.getSettings().setJavaScriptEnabled(true);
        web_view.loadUrl("https://touch.facebook.com/");
        web_view.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        web_view.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                if (progress < 100) {
                    progressDialog.show();
                }
                if (progress == 100) {
                    progressDialog.dismiss();
                }
            }
        });
    }
}

주요 코드 설명

  • setDefaultTextEncodingName("utf-8"): WebView가 웹 콘텐츠를 해석할 때 사용할 기본 문자 인코딩을 UTF-8로 지정합니다. 이 부분이 이 예제의 핵심입니다.
  • setJavaScriptEnabled(true): JavaScript 실행을 허용하여 동적인 웹 페이지가 정상적으로 동작하도록 합니다.
  • WebViewClient: shouldOverrideUrlLoading()에서 링크를 직접 처리해 외부 브라우저로 전환되지 않고 WebView 내부에서 페이지를 열도록 합니다.
  • WebChromeClient: onProgressChanged()로 로딩 진행률을 감시하며, 로딩 중에는 ProgressDialog를 표시하고 완료되면 닫습니다.

참고: ProgressDialog는 API 레벨 26부터 공식적으로 지원 중단(deprecated)되었습니다. 최신 프로젝트에서는 ProgressBar 또는 Material Design 다이얼로그 사용을 권장합니다.

4단계 — 매니페스트 설정

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

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
    package = "com.example.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에 아무것도 표시되지 않으니 주의하세요.

앱 실행 및 결과 확인

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

안드로이드 WebView 기본 텍스트 인코딩(UTF-8) 설정 방법