Android 프로그래밍 2

본문 바로가기
사이트 내 전체검색


Android 프로그래밍 2
Android 프로그래밍 2

1. 웹뷰 실습

페이지 정보

작성자 관리자 댓글 0건 조회 2,005회 작성일 20-07-06 22:11

본문

1. 웹뷰 실습

1. 새 프로젝트 생성


프로젝트명 : WebView



2. 화면 디자인 수정


파일명 : activity_main.xml 


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#edfaed"
android:padding="0dp"
android:orientation="vertical"
>
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<Button
android:id="@+id/button_load"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load URL"
android:textAllCaps="false"
/>
<Button
android:id="@+id/button_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back"
android:textAllCaps="false"
android:enabled="false"
/>
<Button
android:id="@+id/button_forward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Forward"
android:textAllCaps="false"
android:enabled="false"
/>
</LinearLayout>
<WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
</LinearLayout>



3. 메인 액티비티 수정


파일명 : MainActivity.kt


package kr.co.leelab.webview

import android.content.Context
import android.graphics.Bitmap
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
private val url = "https://www.leelab.co.kr"

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

// Get the web view settings instance
val settings = web_view.settings

// Enable java script in web view
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


// Zoom web view text
settings.textZoom = 125


// Enable disable images in web view
settings.blockNetworkImage = false
// Whether the WebView should load image resources
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
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)
settings.allowUniversalAccessFromFileURLs = true
settings.allowFileAccess = true

// WebView settings
web_view.fitsSystemWindows = true


/*
if SDK version is greater of 19 then activate hardware acceleration
otherwise activate software acceleration
*/
web_view.setLayerType(View.LAYER_TYPE_HARDWARE, null)


// Set web view client
web_view.webViewClient = object: WebViewClient() {
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
// Page loading started
// Do something
toast("Page loading.")

// Enable disable back forward button
button_back.isEnabled = web_view.canGoBack()
button_forward.isEnabled = web_view.canGoForward()
}

override fun onPageFinished(view: WebView, url: String) {
// Page loading finished
// Display the loaded page title in a toast message
toast("Page loaded: ${view.title}")

// Enable disable back forward button
button_back.isEnabled = web_view.canGoBack()
button_forward.isEnabled = web_view.canGoForward()
}
}
// Set web view chrome client
web_view.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView, newProgress: Int) {
progress_bar.progress = newProgress
}
}


// Load button click listener
button_load.setOnClickListener {
// Load url in a web view
web_view.loadUrl(url)
}


// Back button click listener
button_back.setOnClickListener {
if (web_view.canGoBack()) {
// Go to back history
web_view.goBack()
}
}


// Forward button click listener
button_forward.setOnClickListener {
if (web_view.canGoForward()) {
// Go to forward history
web_view.goForward()
}
}

}
// Method to show app exit dialog
private fun showAppExitDialog() {
val builder = AlertDialog.Builder(this)

builder.setTitle("Please confirm")
builder.setMessage("No back history found, want to exit the app?")
builder.setCancelable(true)

builder.setPositiveButton("Yes", { _, _ ->
// Do something when user want to exit the app
// Let allow the system to handle the event, such as exit the app
super@MainActivity.onBackPressed()
})

builder.setNegativeButton("No", { _, _ ->
// Do something when want to stay in the app
toast("thank you.")
})

// Create the alert dialog using alert dialog builder
val dialog = builder.create()

// Finally, display the dialog when user press back button
dialog.show()
}



// Handle back button press in web view
override fun onBackPressed() {
if (web_view.canGoBack()) {
// If web view have back history, then go to the web view back history
web_view.goBack()
toast("Going to back history")
} else {
// Ask the user to exit the app or stay in here
showAppExitDialog()
}
}
}

// Extension function to show toast message
fun Context.toast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}



4. 권한설정 


파일명 : AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="kr.co.leelab.webview">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>



5. 실행


1.PNG


댓글목록

등록된 댓글이 없습니다.


개인정보취급방침 서비스이용약관 모바일 버전으로 보기 상단으로

TEL. 063-469-4551 FAX. 063-469-4560 전북 군산시 대학로 558
군산대학교 컴퓨터정보공학과

Copyright © www.leelab.co.kr. All rights reserved.