Home > OS >  Kotlin WebView refresh button
Kotlin WebView refresh button

Time:09-01

i googled a bit how to make a refresh button but i didn't really figured out how to make it. I already have the button in my activity_main but nothing in my MainActivity.kt yet. So my problem is now the function of the button to refresh the page again.

This is my Activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

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="match_parent"
    android:layout_height="match_parent"
    tools:ignore="MissingConstraints"
    tools:layout_editor_absoluteX="8dp"
    tools:layout_editor_absoluteY="8dp" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true"
        android:text="REFRESH"
        android:id="@ id/button"
        tools:ignore="MissingConstraints" />

</androidx.constraintlayout.widget.ConstraintLayout>

And this is my MainActivity.kt

    package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Button



class MainActivity : AppCompatActivity() {


    private lateinit var webView: WebView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        webView = findViewById(R.id.webview)
        webView.settings.setJavaScriptEnabled(true)
        webView.setInitialScale(1);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setSupportZoom(true);



        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                if (url != null) {
                    view?.loadUrl(url)
                }
                return true
            }
        }
        webView.loadUrl("example.com")



    }
}

CodePudding user response:

You can try adding this:

findViewById<Button>(R.id.button).setOnClickListener { 
    webView.reload()
}
  • Related