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

안드로이드 WebView 화면에 꽉 차게 설정하는 방법 (단계별 가이드)

개요

이 튜토리얼에서는 안드로이드 앱에서 WebView가 기기 화면 크기에 딱 맞게 표시되도록 설정하는 방법을 단계별로 알아봅니다. 레이아웃 XML 작성부터 자바 코드 구현, 인터넷 권한 설정까지 전체 과정을 코드 예제와 함께 설명합니다.

1단계: 새 프로젝트 생성

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

2단계: 레이아웃 파일(activity_main.xml) 작성

다음 코드를 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>

위 코드에서는 tutorialspoint.com 웹사이트를 표시하기 위한 WebView를 배치했습니다. layout_widthlayout_height를 모두 match_parent로 지정하여 WebView가 화면 전체를 채우도록 설정합니다.

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.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
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().setLightTouchEnabled(true);
      web_view.getSettings().setJavaScriptEnabled(true);
      web_view.getSettings().setGeolocationEnabled(true);
      web_view.setSoundEffectsEnabled(true);
      web_view.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
      web_view.getSettings().setUseWideViewPort(true);
      web_view.loadUrl("https://www.tutorialspoint.com/");
      web_view.setWebChromeClient(new WebChromeClient() {
         public void onProgressChanged(WebView view, int progress) {
            if (progress < 100) {
               progressDialog.show();
            }
            if (progress == 100) {
               progressDialog.dismiss();
            }
         }
      });
}
}

위 코드의 핵심 포인트는 다음과 같습니다.

  • setUseWideViewPort(true): HTML의 viewport 메타 태그를 지원하여 콘텐츠가 화면 너비에 맞게 조정됩니다.
  • setLayoutAlgorithm(LayoutAlgorithm.NORMAL): 화면에 맞춰 레이아웃을 재구성하도록 설정합니다.
  • setJavaScriptEnabled(true): 대부분의 웹페이지가 정상적으로 동작하도록 자바스크립트를 활성화합니다.
  • ProgressDialog: 페이지 로딩 진행률에 따라 로딩 다이얼로그를 표시하거나 숨깁니다.

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.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 화면에 꽉 차게 설정하는 방법 (단계별 가이드)

이렇게 하면 WebView가 기기 화면 전체에 맞게 확장되어 웹 콘텐츠가 자연스럽게 표시되는 것을 확인할 수 있습니다.