Instantly share code, notes, and snippets.

@nanoxd /MainActivity.kt Secret
Created Mar 22, 2017

Embed
What would you like to do?
Save last url used in an Android Webview as well as handle back button presses
package com.pxelated.app
import android.app.Activity
import android.content.SharedPreferences
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.KeyEvent
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.TextView
class MainActivity : AppCompatActivity() {
companion object {
val LAST_URL = "lastUrl"
}
// Lazy load the webview with all of our configuration
val webview: WebView by lazy {
val webview = findViewById(R.id.webview) as WebView
webview.settings.javaScriptEnabled = true
webview.settings.domStorageEnabled = true
webview.setWebChromeClient(WebChromeClient())
webview.setWebViewClient(WebViewClient())
webview
}
val prefs: SharedPreferences by lazy {
applicationContext.getSharedPreferences(applicationContext.packageName, Activity.MODE_PRIVATE)
}
val lastOrMainUrl: String by lazy {
prefs.getString(MainActivity.LAST_URL, BuildConfig.URL)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
webview.loadUrl(lastOrMainUrl)
}
override fun onPause() {
super.onPause()
// Save the last url visited for this user
prefs.edit()
.putString(MainActivity.LAST_URL, webview.url)
.commit() // .apply can also be used here _へ__(‾◡◝ )>
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
// Check if the key event was the Back button and if there's history
if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
webview.goBack()
return true
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (exit the activity or go to previous activity)
return super.onKeyDown(keyCode, event)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment