Android/Kotlin

WebView

lipnus 2018. 11. 27. 18:56
반응형


1.Permission

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



2.WebView

class MainActivity : AppCompatActivity() {

@RequiresApi(Build.VERSION_CODES.KITKAT)

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

setButtons()
setWebView()

}

fun setWebView(){

var url: String? = "https://naver.com"

// 웹뷰의 인스턴스를 가져온다
val settings = webView.settings

// 자바스크립트 사용가능 유무
settings.javaScriptEnabled = true

// cache유무
settings.setAppCacheEnabled(true)
settings.cacheMode = WebSettings.LOAD_DEFAULT
settings.setAppCachePath(cacheDir.path)


// zoom
settings.setSupportZoom(true)
settings.builtInZoomControls = true
settings.displayZoomControls = true


// 텍스트만 zoom
//settings.textZoom = 125


// 웹뷰에서 이미지 보지 않기설정
settings.blockNetworkImage = false
// 웹뷰가 이미지의 리소스를 로드할 것인지 유무
settings.loadsImagesAutomatically = true


// More web view settings
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
webView.fitsSystemWindows = true

/* SDK version 19이상이면 하드웨어가속, 그렇지 않으면 소프트웨어 가속 */
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null)
webView.loadUrl(url)


// Set web view client
webView.webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
// Page loading started
// Do something
Log.d("SSS","OnPageStart: " + url)
}

override fun onPageFinished(view: WebView, url: String) {
// Page loading finished
// Enable disable back forward button
Log.d("SSS","페이지 로딩 종료")

}
}
}


fun setButtons(){

link1_btn.setOnClickListener {
webView.loadUrl("http://naver.com")
}

link2_btn.setOnClickListener {
webView.loadUrl("http://sunpil.tistory.com")
}
}
}


반응형