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.
Asked
Active
Viewed 1,771 times
0
-
I want to acces button inside my activity to pass intent with extras from one my fragment. – Nabeel K Dec 09 '15 at 13:37
-
okay wait. I am trying those answers. thank you – Nabeel K Dec 09 '15 at 14:21
3 Answers
1
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

Jose Angel Maneiro
- 1,226
- 9
- 20
1
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
}
});

rd7773
- 409
- 3
- 13
-
This is a bad practice as this would decrease the reusability of this fragment as it would always expect its parent activity to have a button with id "button1" – Rishabh Dec 09 '15 at 12:37
-
@Rishabh it depends on the requirement , if the fragment is only to be used with a single parent activity , this way would be the shortest and easy code for a beginner – rd7773 Dec 09 '15 at 13:21
1
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
}

Rishabh
- 386
- 1
- 9