Search code examples
kotlinbuttonfragment

Problem trying to access a bottom from fragment


First of all sorry from my bad english. I'm newby with android and kotlin. I', trying to access from a fragment to a bottom in xml layouts. When I create the inflate is Ok because Kotlin recognizes de fragment. But when I declarete the view I can't find any id from the layout

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    val view = inflater.inflate(R.layout.fragment_pruebas, container, false)
        view. //<-THE PROBLEM IS HERE I CAN'T SHOW THE BUTTON'S ID NEITHER IMPORT THE LAYOUT 
    return view
}

Solution

  • You are in the incorrect function, you have to do that on this override fun, you have to use "findViewById" to find your layout element

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            val button: Button = view.findViewById(R.id.button) //Here your id button 
            button.setOnClickListener {  }
        }
    

    And its in this way because you are not using binding, so you can't call your xml elements by the way that you're trying, check this to do something like you want.

    https://developer.android.com/topic/libraries/view-binding