Upgrade to Pro — share decks privately, control downloads, hide ads and more …

WebViewと向き合う

mkeeda
September 25, 2023

 WebViewと向き合う

DroidKaigi.onCompletion { 2023@Online } の発表資料です
https://yumemi.connpass.com/event/289949/

サンプルコード
https://github.com/mkeeda/webview-sandbox

mkeeda

September 25, 2023
Tweet

More Decks by mkeeda

Other Decks in Programming

Transcript

  1. = URL 10 UI elements WebView UI state URL A

    = UI Web A UI elements WebView UI state URL B = UI Web B
  2. WebView 11 UI elements WebView State holder ViewModel UI state

    URL 3. URL 2 . URL (UI event) 1. URL 4. URL
  3. URL 14 WebViewClient shouldOverrideUrlLoading() UI elements WebView UI state URL

    A State holder ViewModel ❌ return true loadUrl() UI state URL B WebViewClient# 
 shouldOverrideUrlLoading() true URL URL UI state URL B
  4. 15 class WebViewModel : ViewModel() { private val _currentUrl =

    MutableStateFlow(Uri.parse("https://www.google.com")) val url: StateFlow<Uri> = _currentUrl.asStateFlow() fun onPageLoad(newUrl: Uri) { _currentUrl.update { currentUrl -> // ೚ҙͷϩδοΫ // … newUrl } } } // Composeableؔ਺ val url by viewModel.url.collectAsStateWithLifecycle() WebScreen( url = url, onUrlChanged = { newUrl -> viewModel.onPageLoad(newUrl) } )
  5. 16 @Composable fun WebScreen( url: Uri, onUrlChanged: (Uri) -> Unit

    ) { AndroidView( factory = { context -> WebView(context).apply { webViewClient = MyWebViewClient(onUrlChanged) } }, update = { webView -> webView.loadUrl(url.toString()) } ) } class MyWebViewClient( private val onUrlChanged: (Uri) -> Unit ) : WebViewClientCompat() { override fun shouldOverrideUrlLoading( view: WebView, request: WebResourceRequest ): Boolean { onUrlChanged(request.url) return true } }
  6. WebView UI state 
 https://github.com/mkeeda/webview-sandbox WebView 17 Do not call

    WebView#loadUrl(String) with the request's URL and then return true. This unnecessarily cancels the current load and starts a new load with the same URL. https://developer.android.com/reference/android/webkit/WebViewClient