はじめに
今回はJetpackComposeのAndroidViewを使ってWebViewを実装していきます
コード
@Composable
fun WebViewScreen() {
var state by remember { mutableStateOf(WebViewState()) }
val context = LocalContext.current
// WebViewを表示
AndroidView(
factory = { ctx ->
WebView(ctx).apply {
settings.javaScriptEnabled = true
webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView, url: String, favicon: android.graphics.Bitmap?) {
super.onPageStarted(view, url, favicon)
state = state.copy(isLoading = true, currentUrl = url) // 状態を更新
}
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
state = state.copy(isLoading = false) // 読み込み完了時に状態更新
}
override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) {
super.onReceivedError(view, errorCode, description, failingUrl)
state = state.copy(error = description) // エラー時の状態更新
}
}
loadUrl("https://www.example.com")
}
},
modifier = Modifier.fillMaxSize()
)
// ローディングインジケーター
if (state.isLoading) {
CircularProgressIndicator()
}
// エラー表示
state.error?.let {
Text(text = "Error: $it")
}
}
data class WebViewState(
val currentUrl: String = "",
val isLoading: Boolean = false,
val error: String? = null
)
最後に
accompanistにWebViewがあったのですが、Deperecatedになっていたので簡易的なものを自前で実装してみました
ど