【发布时间】:2019-07-02 04:26:53
【问题描述】:
我一直在尝试在片段中加载 webview,但网上发布的方法都没有奏效,导致我的应用程序崩溃。我有一个包含 5 个片段的底部导航菜单,我需要每个片段在 webview 中加载不同的网站。
以下是其中一个片段的 kotlin 文件:
class DaumFrag : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_daum, container, false)
val mWebView: WebView? = view?.findViewById(R.id.webviewdaum) as WebView
mWebView?.loadUrl("https://www.daum.net/")
val webSettings = mWebView?.getSettings()
webSettings?.setJavaScriptEnabled(true)
// Force links and redirects to open in the WebView instead of in a browser
mWebView?.setWebViewClient(WebViewClient())
return v
}
}
下面是片段的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"
tools:context=".DaumFrag">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="daum"/>
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/webviewdaum"/>
</FrameLayout>
下面是mainactivity的xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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=".MainActivity" android:orientation="horizontal">
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@+id/BottomTab"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintVertical_bias="1.0">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/webview"/>
</FrameLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:menu="@menu/bottom_navigation"
android:background="?android:attr/windowBackground"
app:itemTextColor="#000000"
app:labelVisibilityMode="labeled"
android:layout_gravity="bottom"
android:id="@+id/BottomTab"
app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent" android:layout_marginRight="8dp" android:layout_marginStart="8dp"
app:layout_constraintStart_toStartOf="parent" android:layout_marginLeft="8dp"/>
</androidx.constraintlayout.widget.ConstraintLayout>
【问题讨论】:
-
如果您发布崩溃日志的相关部分会有所帮助,我们真的不知道是什么导致您的应用崩溃。
-
创建视图后尝试加载网页。
标签: android xml android-studio kotlin