package carleton.comp2601.webviewcompose
import android.os.Bundle
import android.util.Log
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.viewinterop.AndroidView
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
// Calling the composable function
// to display element and its contents
MainContent()
}
}
}
// Creating a composable
// function to display Top Bar
@Composable
fun MainContent() {
var curURL by remember { mutableStateOf("https://news.ycombinator.com") }
var navigate by remember { mutableStateOf("") }
Scaffold(
// topBar = { TopAppBar(title = {Text("COMP 2601")})},
topBar = {
Row {
ClickableText(
AnnotatedString(text = "Back"),
onClick = {
navigate = "back"
Log.d("webviewCompose", "navigate = back")
}
)
URLBar(curURL = curURL, updateURL = { curURL = it })
}
},
content = { MyContent(curURL = curURL, updateURL = { curURL = it },
navigate = navigate, resetNavigate = { navigate = ""}) }
)
}
@Composable
fun URLBar(curURL: String, updateURL: (String) -> Unit) {
var newURL = ""
TextField(
value = curURL,
//onFocusChange = { updateURL(newURL) },
//onValueChange = { updatedURL: String -> newURL = updatedURL},
onValueChange = updateURL,
label = { Text("Enter URL here") }
)
}
@Composable
fun MyContent(curURL: String, updateURL: (String) -> Unit,
navigate: String, resetNavigate: () -> Unit){
class ObservableWebViewClient : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
if (url != null) {
updateURL(url)
}
return false
}
}
// Adding a WebView inside AndroidView
// with layout as full screen
AndroidView(factory = {
WebView(it).apply {
// layoutParams = ViewGroup.LayoutParams(
// ViewGroup.LayoutParams.MATCH_PARENT,
// ViewGroup.LayoutParams.MATCH_PARENT
// )
webViewClient = ObservableWebViewClient()
loadUrl(curURL)
}
}, update = {
if (navigate == "back") {
Log.d("webviewCompose", "Navigating back")
it.goBack()
val theURL = it.url
if (theURL != null) {
updateURL(theURL)
}
resetNavigate()
} else {
it.loadUrl(curURL)
}
})
}
// For displaying preview in
// the Android Studio IDE emulator
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MainContent()
}