1
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?

Android WebView の基本的な開き方

1
Posted at

Android アプリでWebViewを使ってWebページを表示する方法をメモします。

レイアウトに WebView を配置する

まずは表示用の WebView をレイアウトに配置します。

<WebView
    android:id="@+id/webView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Activity で WebView を初期化し、URL を読み込む

次に Kotlin側で WebView を設定します。

class WebViewActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_webview)

        val webView = findViewById<WebView>(R.id.webView)

        webView.webViewClient = WebViewClient()
        webView.settings.javaScriptEnabled = true
        webView.loadUrl("https://www.google.com")
    }
}

WebViewClient を設定しない場合ページ遷移時、リンククリック時に外部ブラウザが起動してしまいます。

webView.webViewClient = WebViewClient()

実務には以下の設定を追加することが多いです。

webView.settings.apply {
    javaScriptEnabled = true    // WebViewでJavaScriptの実行を許可する
    domStorageEnabled = true    // Web Storage を有効にする
    loadWithOverviewMode = true // ページ全体が画面内に収まるようリサイズする
    useWideViewPort = true      // WebViewにViewportを使わせる
}
1
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
1
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?