Home > Enterprise >  How do i use findViewById in a fragment instead of an activity?
How do i use findViewById in a fragment instead of an activity?

Time:05-19

So I'm building this calculator and I used activities but now I have to use fragments instead. I had these buttons implemented but now that I've moved them in a fragment I cant use findViewById. How can I assign the id to my variables?enter image description here

CodePudding user response:

Notice that onViewCreated has a view parameter. You can call it on that so like view.findViewById(R.id.text)

CodePudding user response:

I would suggest to use viewBinding, and if you are not comfortable with that then you should do it in onCreateView() method of your fragment. Like this,

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    view = inflater.inflate(R.layout.your_layout_file, container, false)
val imageView = view.findViewById<ImageView>(R.id.id_of_imageview)
    return view
}
  • Related