ImageButton OnClickListener not working

So I have the following ImageButton in a fragment:


And the following fragmentActivity.kt

class Home : Fragment()  {

    override public fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view: View? = inflater.inflate(R.layout.fragment_home, container, false)
        val moneyButton: ImageButton = view?.findViewById( as ImageButton

        val result = MyAppApplication()
        var money =

        moneyButton.setOnClickListener(View.OnClickListener {
            Toast.makeText(activity, "TESTING BUTTON CLICK 1", Toast.LENGTH_SHORT).show()

        return view

I also tried to use the "normal" Kotline setOnClickListener

moneyButton.setOnClickListener {
            Toast.makeText(activity, "TESTING BUTTON CLICK 1", Toast.LENGTH_SHORT).show()

The App dosent crash and dosent freeze, it just dont work

I also tried to replace the Toast with a throw, but that wont be exceuted either. Maybe you can find my mistake?

5 answers

  • answered 2017-06-17 18:16 Zhyano

    First of all, do you even know that this code is executed? That the listener is set? Maybe try to use the Log class (should be the same in Kotlin as in Java).
    Also, val result = MyAppApplication() var money = looks suspicious to me. Are you trying to create a new Application instance?

  • answered 2017-06-17 18:16 user8176963

    Have you tried to set android:clickable="true" for your ImageButton in xml file?

  • answered 2017-06-17 18:16 shiftpsh

    Try initializing your click listener in onActivityCreated. It's called after onCreateView so it'll ensure that view is inflated.

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        val moneyButton: ImageButton = activity.findViewById( as ImageButton
        moneyButton.setOnClickListener {
            Toast.makeText(activity, "TESTING BUTTON CLICK 1", Toast.LENGTH_SHORT).show()

  • answered 2017-06-17 18:16 Prabjot Kaur

    You need to create a 'new' listener object in the arguments section. just type new and pick the first one that comes in the drop down list, and enter the code in curly braces.

    moneyButton.setOnClickListener(new View.OnItemClickListener(){@override
    public void onItemClick{
    /*your code here*/});

  • answered 2017-06-17 18:16 DaveNOTDavid

    Strange, I just tried your code snippets on my platform, and the Toast pops up just fine... Try changing the first arg of Toast to view.context instead so it'd look something like:

    Toast.makeText(view.context, "TESTING BUTTON CLICK 1", Toast.LENGTH_SHORT).show()

    Let me know if that makes a difference.