【发布时间】:2017-06-10 10:58:30
【问题描述】:
我正在尝试从 Fragment 访问 WebView,而 kotlin 一直在说:
kotlin.TypeCastException: null cannot be cast to non-null type android.webkit.WebView
我尝试将其设为默认值,然后对其进行初始化,但这也不起作用。关于如何使它工作的任何建议?
我的代码:
private lateinit var webView: WebView
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater!!.inflate(R.layout.editor_edit_fragment, container, false)
webView = view.findViewById(R.id.webview) as WebView
resumeWebView()
return view
}
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webview" />
</LinearLayout>
【问题讨论】:
-
看起来
view.findViewById(R.id.webview)正在返回null。您确定在R.layout.editor_edit_fragment中有一个具有该ID 的视图吗? -
我完全确定。刚刚检查过
-
添加无效?
-
问题是
findViewById出于某种原因返回null,它就在错误中。您可以将其分配给一个可以为空的变量,但这不会让您有任何收获。 -
@alvarlagerlof 请同时出示您的 editor_edit_fragment.xml。
标签: android android-fragments android-webview kotlin android-view