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 :
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