Rajendrakumar Dabhi

Oct 11, 2021

1 min read

Loading Webpage into Android App Screen

When there is requirement for loading web of term and condition we. are wondering how to do that and what are the basic config to do so here it is.

Create an Activity and add below code in its mainactivity.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:orientation = "horizontal"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
xmlns:android = "http://schemas.android.com/apk/res/android"
>
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>

Create Activity with obtaining the web-view reference

class MainAcitivity :AppCompatActivity() {

lateinit var binding:ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding=ActivityMainBinding.inflate(layoutInflater)
var url=intent.getStringExtra("UrltoLoad").toString() setContentView(binding.root)
initWebSetting(binding.webview)
binding.webview.loadUrl(url)
}

//Basic Setting that are used with webview Customize it acording to your requirement
fun initWebSetting(webView: WebView) {
webView.webViewClient=CustomWebClient()
val setting: WebSettings = webView.getSettings()
setting.javaScriptEnabled = true
setting.allowFileAccess = true
setting.setAppCacheEnabled(true)
setting.databaseEnabled = true
setting.domStorageEnabled = true
setting.cacheMode = WebSettings.LOAD_DEFAULT
setting.useWideViewPort = true
setting.loadWithOverviewMode = true
setting.layoutAlgorithm = WebSettings.LayoutAlgorithm.NORMAL
}


//By Customizing this class you can handle event that come from the webview
class CustomWebClient : WebViewClient() {
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap) {
super.onPageStarted(view, url, favicon)
}

override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
return true
}
}
}

When you want to open any url(e.g term and condition,info windo,contact us)

You just need to pass the url as IntentData(UrltoLoad) of the webpage and you webpage will be loaded into the new screen.

fun loadWebView(){
var intent=Intent(this,WebviewActivity::class.java)
intent.putExtra("UrltoLoad","https:google.com") //pass url here
startActivity(intent)
}

Add internet permission in the manifest.

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

Thats it,