본문 바로가기
안드로이드 자바

[Java][Android] 안드로이드 - 웹뷰(WebView) 만들기

by teamnova 2021. 2. 5.

웹뷰란? 

안드로이드 앱 내에서 웹페이지를 표시하는 뷰 입니다.

 

[참고]

developer.android.com/reference/android/webkit/WebView

developer.android.com/guide/webapps/webview


예제

버튼을 누르면 웹 페이지 화면으로 이동하는 예제를 만들어보겠습니다.

 

먼저 xml에 버튼을 선언합니다.

 

<activity_main.xml>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <WebView
        android:id="@+id/webview"
        android:layout_width="405dp"
        android:layout_height="684dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.893">
    </WebView>

    <Button
        android:id="@+id/create_button"
        android:layout_width="183dp"
        android:layout_height="58dp"
        android:layout_x="84dp"
        android:layout_y="299dp"
        android:text="WebView 실행하기"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

<MainActivity>

버튼 이벤트를 사용하려면, 클래스에서 button을 findViewById로 선언해주고, 클릭 리스너를 만들어 줘야 합니다.

스틱 코드를 활용한다면, 클래스에서 'bu'까지만 작성 했을 때 버튼 클릭이벤트가 나타납니다.

 

버튼 클릭 이벤트를 클릭하면 코드가 한 번에 작성이 되서 편리합니다.

변수명, xml에 작성된 버튼의 id 값만 변경하면 되니 빠르게 코딩이 가능합니다.

예시)


이제, 버튼을 클릭했을 떄, 웹 페이지로 이동 할 수 있도록 WebView 코드를 추가합니다.

 

스틱코드를 통해 불러온 코드에는 xml에 생성 되어 있는 webView id, 이동할 홈페이지 주소 부분이

비어 있으므로 원하는 값을 입력해 주시면 됩니다.

예시)


여기까지 마치면, 아래 버튼을 클릭할때마다 입력한 웹페이지로 이동하는 것을 확인할 수 있습니다.

webView 실행 결과

 

 

활용한 스틱코드

 

버튼 이벤트) stickode.com/detail.html?no=1885

웹뷰) stickode.com/detail.html?no=1886