안드로이드 WebView 포커스 추가 방법
이 예제는 안드로이드 앱에서 WebView(웹뷰)에 포커스를 추가하는 방법을 단계별로 설명합니다. WebView는 앱 내부에서 웹 페이지를 직접 표시할 수 있게 해주는 안드로이드의 핵심 컴포넌트 중 하나입니다.
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>위 코드에서는 google.com 페이지를 표시하기 위해 화면 전체를 채우는 WebView 하나를 배치했습니다.
3단계: MainActivity.java 작성
src/MainActivity.java 파일에 다음 코드를 추가합니다.
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
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);
WebView web_view = findViewById(R.id.web_view);
web_view.loadUrl("https://www.google.com/");
web_view.requestFocus();
web_view.getSettings().setLightTouchEnabled(true);
}
}여기서 사용된 핵심 메서드는 다음과 같습니다.
loadUrl() – 지정한 URL의 웹 페이지를 로드합니다.
requestFocus() – WebView에 포커스를 요청하여 키보드 입력 등의 이벤트를 받을 수 있도록 합니다.
setLightTouchEnabled(true) – 가벼운 터치(light touch) 동작으로도 링크 선택이 가능하도록 설정합니다.
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(실행) 아이콘을 클릭하세요. 기기 목록에서 본인의 모바일 기기를 선택하면 화면에 아래와 같은 결과가 표시됩니다.
