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

안드로이드 웹뷰(WebView)에서 세로 스크롤바 활성화하는 방법

이 예제는 안드로이드 웹뷰(WebView)에서 세로 스크롤바를 활성화하는 방법과 함께, 기본 텍스트 인코딩(utf-8)을 설정하는 과정까지 단계별로 설명합니다.

핵심 포인트

웹뷰에서 세로 스크롤바를 활성화하는 핵심은 setVerticalScrollBarEnabled(true) 메서드입니다. 이 메서드를 호출하면 콘텐츠가 화면 높이를 초과할 때 스크롤바가 자동으로 표시됩니다.

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 페이지를 표시하기 위해 웹뷰를 사용했습니다. 웹뷰가 부모 레이아웃 전체를 차지하도록 match_parent로 설정했습니다.

3단계 — MainActivity.java 작성

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.CookieManager;
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.setVerticalScrollBarEnabled(true);
        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();
                }
            }
        });
    }
}

주요 코드 설명

  • setVerticalScrollBarEnabled(true): 웹뷰의 세로 스크롤바를 활성화합니다.
  • setDefaultTextEncodingName("utf-8"): 한글 등 다국어 콘텐츠가 깨지지 않도록 기본 인코딩을 UTF-8로 지정합니다.
  • setJavaScriptEnabled(true): 웹페이지의 자바스크립트 실행을 허용합니다.
  • shouldOverrideUrlLoading(): 링크 클릭 시 외부 브라우저가 아닌 웹뷰 내부에서 페이지가 열리도록 처리합니다.
  • onProgressChanged(): 로딩 진행률에 따라 ProgressDialog를 표시하거나 숨깁니다.

4단계 — 매니페스트 설정

AndroidManifest.xml에 아래 코드를 추가합니다. 인터넷 사용 권한(INTERNET) 선언은 필수입니다.

<?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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바에서 실행(Run) 아이콘을 클릭하세요. 실행 기기 목록에서 본인의 모바일 기기를 선택하면, 모바일 화면에 아래와 같은 결과가 표시됩니다.

안드로이드 웹뷰(WebView)에서 세로 스크롤바 활성화하는 방법