Home > Enterprise >  cant get any component in fragment class (kotlin)
cant get any component in fragment class (kotlin)

Time:05-01

i manually created a fragment. but cant declare a component like web view or button. when i paste and edit "val webview: WebView ..." there is error "Fragment(R.layout.fragment_htmlviewer)" too. i dont know how to do, when i create from android studio, it looks like very complicated. so i watched a video and this is more easy but cant declare components. im very beginner so help me please... my code:

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
}

}

CodePudding user response:

I recommend you to use the binding structure, it is a more preferred structure today. build.gradle(module)

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
}

CodePudding user response:

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

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

this is solution.

  • Related