본문 바로가기
카테고리 없음

[Kotlin App] 웹뷰

by 태옹 2021. 5. 4.

웹뷰

사용자가 웹 브라우저 기능을 앱 안에 직접 포함할 수 있는 위젯

 


 

연습문제 실습

 

 

 

1. menifest.xml파일에 permission주기 - 웹 브라우저 접근 권한

<uses-permission android:name="android.permission.INTERNET"/>

 

2. xml작성

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/edtUrl"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:inputType="textPersonName"
            android:text="https://m.daum.net" />

        <Button
            android:id="@+id/btnGo"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="이동" />

        <Button
            android:id="@+id/btnBack"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="이전" />
    </LinearLayout>

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

 

3. MainActivity.kt작성

package com.cookandroid.kotlinapp0503_2

import android.os.Bundle
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        webView1.webViewClient = CookWebViewClient()    //클래스 객체 생성
        var webSet = webView1.settings
        webSet.javaScriptEnabled = true     //자바스크립트로 만들어진 브라우저에 접근하기 위한 코드

        btnGo.setOnClickListener {
            webView1.loadUrl(edtUrl.text.toString())    //https://m.daum.net
        }
    }
}

class CookWebViewClient : WebViewClient() {
    override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
        return super.shouldOverrideUrlLoading(view, request)
    }
}

댓글