无法获取片段 class 中的任何组件(kotlin)

cant get any component in fragment class (kotlin)

我手动创建了一个片段。但不能声明像 Web 视图或按钮这样的组件。当我粘贴和编辑“val webview: WebView ...”时,也出现错误“Fragment(R.layout.fragment_htmlviewer)”。我不知道该怎么做,当我从 android studio 创建时,它看起来很复杂。所以我看了一个视频,这更容易但不能声明组件。我是初学者所以请帮助我...我的代码:

fragment_htmlviewer.xml

<WebView
    android:id="@+id/htmlViewer"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/floating_action_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="16dp"
    android:contentDescription="@string/fabdescription"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:srcCompat="@drawable/ic_left_arrow_icon" />

HtmlViewerFragment.kt

class HtmlViewerFragment : Fragment(R.layout.fragment_htmlviewer) {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

}

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    return super.onCreateView(inflater, container, savedInstanceState)

}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val webview: WebView = getView()!!.findViewById<View>(R.id.htmlViewer) as WebView
}

}

我推荐你使用绑定结构,这是今天更喜欢的结构。 build.gradle(模块)

buildFeatures {
        viewBinding true
        dataBinding true
    }

HtmlViewerFragment

private var _binding: FragmentHtmlViewerBinding? = null
    private val binding
        get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    _binding = FragmentHtmlViewerBinding.inflate(inflater, container, false)
//.. this is write code
binding.apply{
//eg:
    htmlViewer.setOnClickListener{

}
}
return binding.root
}
override fun onStart() {
    super.onStart()
    htmlViewer = requireView().findViewById(R.id.htmlViewer) as WebView

    htmlViewer!!.loadUrl("https://www.google.com")
}

这是解决方案。

htmlViewer = requireView().findViewById(R.id.htmlViewer) as WebView

固定