fragment のwebviewにて loadurlをしてウェブページを表示します。
言語:kotlin
完成図
ボタン押下でフラグメントの表示と、WebViewの表示
さらに任意のURLを表示
MainActivity.kt
btn_fragmentにてfragment遷移します。
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) btn_fragment.setOnClickListener { val webViewFragment = WebViewFragment() val fragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.add(R.id.fragment_container, webViewFragment) fragmentTransaction.commit() } } }
activity_main.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=".MainActivity"> <Button android:id="@+id/btn_fragment" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintTop_toTopOf="parent" app:layout_constraintLeft_toLeftOf="parent" android:text="@string/btn_fragment" />
WebViewFragment.kt
package com.example.skillschallenge 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 android.webkit.WebViewClient const val NETWORK_ADDRESS ="https://tanukigolf.com/" class WebViewFragment : Fragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // WebViewのデバッグを有効にする WebView.setWebContentsDebuggingEnabled(true) val v: View = inflater.inflate(R.layout.fragment_web_view, container, false) val mWebView = v.findViewById<View>(R.id.web_view) as WebView //webview内のJavaScriptを有効にする mWebView.settings.javaScriptEnabled = true mWebView.webViewClient = WebViewClient() mWebView.loadUrl(NETWORK_ADDRESS) return v } }
fragment_web_view.xml
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" tools:context=".WebViewFragment"> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/hello_blank_fragment" /> <WebView android:id="@+id/web_view" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent"> </WebView> </FrameLayout>
コメント