Herkese merhaba,

Bu yazımda Android Studio üzerinde Kotlin kullanarak WebView kullanımını anlatacağım. İlk olarak xml dosyamıza WebView nesnesini ekliyoruz. Aşağıda kodları bulunmaktadır.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">


    <RelativeLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <WebView
            android:id="@+id/webview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_centerInParent="true" />
    </RelativeLayout>
</android.support.constraint.ConstraintLayout>

Gelelim Kotlin kısmına;
İlk olarak WebView tanımlamasını yapmamız gerekmektedir.

lateinit var webView: WebView

Şimdi gelelim onCreate() metoduna:

webView = findViewById(R.id.webview)

webView.webViewClient = object : WebViewClient() {
    override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
        view?.loadUrl(url)
        return true
    }
}
webView.loadUrl("https://www.google.com/")

Şimdi kodun tamamına göz atalım:

package com.can.ders

import android.graphics.Color
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import android.webkit.WebView
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
import com.can.ders.R.id.webview
import android.widget.Toast
import android.webkit.WebViewClient
import android.webkit.WebChromeClient
import android.app.Activity
import android.app.ProgressDialog
import android.graphics.Bitmap
import android.util.Log
import android.view.Window
import android.view.Window.FEATURE_PROGRESS
import android.webkit.WebSettings
import java.util.*


class MainActivity : AppCompatActivity() {

    lateinit var webView: WebView

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

        webView = findViewById(R.id.webview)

        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                view?.loadUrl(url)
                return true
            }
        }
        webView.loadUrl("https://www.google.co.in/")
    }

}

Bir sonraki yazımda görüşmek üzere…