4
8

More than 3 years have passed since last update.

Android FragmentにローカルHTMLファイルからWebViewを表示(Kotlin)

Posted at

はじめに

3つのNavigation Buttonがあり、それぞれをFragmentで作ってるとする。
そのうちの1つのFragmentに、ローカルHTMLファイルから読み込んだWebViewを表示する。

イメージはこんなん。日本地図の部分はみなさんが好きなHTMLファイルを用意してください。

3つのNavigation Buttonをどうやって作るかは、:point_down:をみてね!
Android Fragmentの中にタブ付きスワイプビューを作る(kotlin)

HTMLファイルを設置する

何気にこれが苦戦した・・・・

どこに入れるのかが分からんかった。。。

「assets」の名前でフォルダを作成

そこにhtmlファイルを入れる。僕の場合はjapanというフォルダ内にhtmlファイルを入れたので、assets/japan/index.htmlとなる
スクリーンショット 2020-06-07 16.20.50.jpg

Android Studioで見ると、こんな感じ。
スクリーンショット 2020-06-07 16.21.26.jpg

余談だが、Android Studioでjapanフォルダを、assetsフォルダ内にドラッグ&ドロップで追加しようとしても、うまくいかないのだが、、、、
追加できるのはファイルだけ??

WebViewを表示するFragmentを編集

XML

特定のFragmentのxmlを開く。僕の場合はfragment_first.xml

fragment_first.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FirstFragment">

    <WebView
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

スクリーンショット 2020-06-07 16.31.17.jpg

Kotlin

FirstFragment.kt
package com.example.myapplication

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import androidx.appcompat.app.AppCompatActivity

/**
 * A simple [Fragment] subclass.
 */
class FirstFragment : androidx.fragment.app.Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view: View = inflater.inflate(R.layout.fragment_first, container, false)

        //xmlのWebViewで指定したid
        val myWebView: WebView = view.findViewById(R.id.map)

       //javascriptがデフォルトで無効なので、有効にする
        myWebView.settings.javaScriptEnabled = true

        //設置したhtmlファイルへのパス
        myWebView.loadUrl("file:///android_asset/japan/map.html")
        return view
    }

}

普通のwebサイトの場合、loadUrlはこうなる。

myWebView.loadUrl("http://www.example.com")

ただし、今回はプロジェクトフォルダ内に設置したHTMLファイルなので、

myWebView.loadUrl("file:///android_asset/japan/map.html")

みたいな形となるみたい。

4
8
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
4
8