How to pass OnClickListener from Activity to Fragment

I need to pass an OnClickListener object from activity to a Fragment. I can't pass argument to Fragment constructor, so i want to do something like:

Bundle bundle = new Bundle();
bundle.putCustomObject(new OnClickListener(){...});

2 answers

  • answered 2018-07-15 16:19 emandt

    Add a method to the fragment:

    public void setOnClickListener(OnClickListener listener) { mListener = listwner;} 
    

    Call Fragment's method:

    mFragment.setOnClickListener(new OnClickLkstener(.... 
    

  • answered 2018-07-15 16:30 Nelson Almendra

    I think the best approach is to create an interface with a method onClick() and set the callback from the Activity to the Fragment.

    Interface

    public interface FragmentClickListener
    {
        void onClick();
    }
    

    Create a variable and method in Fragment class to receive the FragmentClickListener:

    private FragmentClickListener listener;
    
    public void setOnClickListener(FragmentClickListener listener)
    {
        this.listener = listener;
    }
    

    Then in some method of your Fragment class you can call the listener like this:

    void someMethod()
    {
        if(listener != null) {
            listener.onClick();
        }
    }
    

    In your Activity class define the call back like this:

    fragment.setOnClickListener(new FragmentClickListener(){
        @Override
        public void onClick() {
                //do something here
        }
    });