Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Button setOnClickListener not working in a fragment

So I created a blank fragment and I tried to add a setOnClickListener to a button, but I doesn’t seem to do anything. Im not sure if Im putting it in the right place or not. If I just use the button id without the view, the app just crashes when I open this fragment

class CreateJobFragment : Fragment() {
        // TODO: Rename and change types of parameters
        private var param1: String? = null
        private var param2: String? = null
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            arguments?.let {
                param1 = it.getString(ARG_PARAM1)
                param2 = it.getString(ARG_PARAM2)
            }
        }
    
        override fun onCreateView(
            inflater: LayoutInflater, container: ViewGroup?,
            savedInstanceState: Bundle?
    
        ): View? {
            // Inflate the layout for this fragment
            val view: View = inflater!!.inflate(R.layout.fragment_create_job, container, false)
            view.create_btn.setOnClickListener {
                Log.d("console", "Button pressed")
            }
            return inflater.inflate(R.layout.fragment_create_job, container, false)
        }
    
        companion object {
            @JvmStatic
            fun newInstance(param1: String, param2: String) =
                CreateJobFragment().apply {
                    arguments = Bundle().apply {
                        putString(ARG_PARAM1, param1)
                        putString(ARG_PARAM2, param2)
                    }
                }
        }
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You inflated your view layout once, set a click listener on the button in that layout, and then you completely throw it away, because you inflate your layout all over again and return that second layout, for which you did not set a click listener.

Change

return inflater.inflate(R.layout.fragment_create_job, container, false)

to

return view
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading