코틀린에서 WebView 기능을 구글링해서 코드를 여러가지 추가하면서 테스트하고 적어둔다.
책에 나온 코드는 매우 간단하다.
사실 코드가 간단해도 동작하는데 전혀 문제는 없다.
Project build.gradle
buildscript { ext.kotlin_version = '1.3.72' ext.anko_version='0.10.8'
repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.6.3' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } }
|
앱 build.gradle
apply plugin: 'com.android.application' apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions'
android { compileSdkVersion 29 buildToolsVersion "29.0.3"
defaultConfig { applicationId "com.link2me.android.webview" minSdkVersion 21 targetSdkVersion 29 versionCode 1 versionName "1.0"
}
buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } }
compileOptions { sourceCompatibility = 1.8 targetCompatibility = 1.8 }
}
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.core:core-ktx:1.2.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation "org.jetbrains.anko:anko:$anko_version"
implementation 'com.google.android.material:material:1.1.0' implementation 'androidx.cardview:cardview:1.0.0' // 레이아웃으로 사용할 CardView implementation 'androidx.recyclerview:recyclerview:1.1.0' }
|
import android.app.Activity import android.os.Build import android.os.Bundle import android.view.KeyEvent import android.view.inputmethod.EditorInfo import android.webkit.* import android.widget.Toast import androidx.annotation.RequiresApi import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private lateinit var mWebView: WebView
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)
mWebView = findViewById(R.id.webView) val url: String = "http://link2me.tistory.com/" MyWebView(url)
urlEditText.setOnEditorActionListener{_, actionId, _-> if(actionId == EditorInfo.IME_ACTION_SEARCH){ var url: String = urlEditText.text.toString() if(!(url.contains("http://") || url.contains("https://"))){ url = "http://${url}" } MyWebView(url) true } else { false } }
}
fun MyWebView(url: String){ mWebView.apply { settings.javaScriptEnabled = true // Enable and setup web view cache settings.setAppCacheEnabled(true) settings.cacheMode = WebSettings.LOAD_DEFAULT settings.setAppCachePath(cacheDir.path) // Enable zooming in web view settings.setSupportZoom(true) settings.builtInZoomControls = true settings.displayZoomControls = true // Enable disable images in web view settings.blockNetworkImage = false // Whether the WebView should load image resources settings.loadsImagesAutomatically = true
settings.domStorageEnabled = true if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { settings.safeBrowsingEnabled = true // api 26 } //settings.pluginState = WebSettings.PluginState.ON settings.useWideViewPort = true settings.loadWithOverviewMode = true settings.javaScriptCanOpenWindowsAutomatically = true if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { settings.mediaPlaybackRequiresUserGesture = false }
// More optional settings, you can enable it by yourself settings.domStorageEnabled = true settings.setSupportMultipleWindows(true) settings.loadWithOverviewMode = true settings.allowContentAccess = true settings.setGeolocationEnabled(true) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { settings.allowUniversalAccessFromFileURLs = true }
settings.allowFileAccess = true
// WebView settings mWebView.fitsSystemWindows = true
mWebView.webViewClient = MyWebViewClient(this@MainActivity) } mWebView.loadUrl(url) }
class MyWebViewClient internal constructor(private val activity: Activity) : WebViewClient() {
@RequiresApi(Build.VERSION_CODES.LOLLIPOP) override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean { val url: String = request?.url.toString(); view?.loadUrl(url) return true }
override fun shouldOverrideUrlLoading(webView: WebView, url: String): Boolean { webView.loadUrl(url) return true }
override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) { Toast.makeText(activity, "Got Error! $error", Toast.LENGTH_SHORT).show() } }
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) { mWebView.goBack() return true } return super.onKeyDown(keyCode, event) }
override fun onBackPressed() { if(mWebView.canGoBack()){ mWebView.goBack() // 이전 페이지로 갈 수 있다면 이동하고 } else { super.onBackPressed() // 더 이상 이전 페이지가 없을 때 앱이 종료된다. } } }
|
XML Layout 만드는 방법은 별도 적지 않고 테스트한 소스코드를 첨부한다.
WebView.zip