Search code examples
androidandroid-fragmentsbuttononclicklistenerandroid-fragmentactivity

onClickListener on button in fragment does nothing


I have a fragment that has a button in and have added a button listener and this is not giving any errors, but the onClick doesn't seem to be called when I click the button. I have tried adding the button listener in the onActivityCreated function but this still doesn't work. Thanks.

package com.aaronnebbs.table_booker.Fragments;

import android.content.Context;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


import com.aaronnebbs.table_booker.Objects.Session;
import com.aaronnebbs.table_booker.R;


public class userInformation extends Fragment {

    private Session session;

    public userInformation() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_user_information, container, false);
        Button viewBookings = (Button) view.findViewById(R.id.bookingsFragmentButton);


        viewBookings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.out.println("Button Clicked");
            }
        });

        Bundle bundle = getArguments();

        if(bundle != null){
            session = (Session)bundle.getSerializable("session");
            System.out.println("IN FRAGMENT: " + session.getUser().getUsername());
        }else{
            System.out.println("NO BUNDLE");
        }

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

       // TextView text = (TextView) getView().findViewById(R.id.usernameFragment);
      //  text.setText("Username: " + session.getUser().getUsername());

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

}

Solution

  • Make sure your fragment_user_information must have Button with bookingsFragmentButton id & You have not assigned onClick by xml like android:onClick="myMethod" & Put toast instead of Log to act as visible effect.

    Edit 1:

     extends Fragment implements View.OnClickListener {
    
    //  onCreateView
    
    viewBookings.setOnClickListener(this);
    

    @Override public void onClick(View v) {

        switch (v.getId())
        {
            case R.id.bookingsFragmentButton:
    
                break;
         }
      }
    
     }
    

    Hope this will make sense.