0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Jetpack ComposeでWebViewを実装する

Posted at

はじめに

今回は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になっていたので簡易的なものを自前で実装してみました

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?