Nabeel K
Nabeel K

Reputation: 6128

Call Button clickListener of activity from fragment?

I have a button inside my activity which contain fragments. From one of the fragment I need to call button, button clickListener and pass an intent with extras to another activity. How can I do this? I searched a lot for this but couldn't find an appropriate solution for this.

Upvotes: 0

Views: 1816

Answers (3)

Rishabh
Rishabh

Reputation: 386

Implement the onClickListener for the button in the activity:

button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
    // get the fragment from the fragment manager
    Fragment frag = getFragmentManager().findFragmentByTag("FRAGMENT TAG");
    Bundle extras = frag.getExtrasForNewActivity();

    /// Your code here this is for Activity
    Intent intent=new Intent(getActivity(),Second.class);
    intent.putExtras(extras);
    startActivity(intent);
 }
});

and in the fragment, create a method like so:

public Bundle getExtrasForNewActivity()
{
    /// return a bundle with values
}

Upvotes: 1

rd7773
rd7773

Reputation: 439

You can write the onclicklistener inside your fragment class as well. Get the button object from your activity and set onclick in your fragment class onActivityCreated method like this ...

Button button = (Button)getActivity().findViewById(R.id.button1);

button .setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            /// Your code here
        }
    });

Upvotes: 1

Jose Angel Maneiro
Jose Angel Maneiro

Reputation: 1316

You can contact your Activity through an interface:

  • First, inside your Fragment:

    public interface ButtonCallback {
    
        //You can add parameters if you need it
    
        void launchAction();
    }
    
    //And when you want comunicate with Activity, launch call
    ((ButtonCallback ) getActivity()).launchAction();
    
  • Then, your Activity must implements YourFragment.ButtonCallback, and override the method you hear the call from the fragment:

    Activity implements YourFragment.ButtonCallback{
    
       @Override
       public void launchAction() {
           //Todo
           //Your intent with extras...
       }
    
    }
    

Regards

Upvotes: 1

Related Questions