Skip to content

Instantly share code, notes, and snippets.

@mstfldmr
Last active March 31, 2022 07:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mstfldmr/fc4fa436f2e553b10865 to your computer and use it in GitHub Desktop.
Save mstfldmr/fc4fa436f2e553b10865 to your computer and use it in GitHub Desktop.
Calling Fragment method from Activity / Activity method from Fragment
/*
* From fragment to activty:
*/
((YourActivityClassName)getActivity()).yourPublicMethod();
/*
* From activity to fragment:
*/
FragmentManager fm = getSupportFragmentManager();
//if you added fragment via layout xml
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentById(R.id.your_fragment_id);
fragment.yourPublicMethod();
//If you added fragment via code and used a tag string when you added your fragment, use findFragmentByTag instead:
YourFragmentClass fragment = (YourFragmentClass)fm.findFragmentByTag("yourTag");
/*
* Better approach:
* Define an interface in the fragment, implement it in the activity
* Call it from the fragment
*/
public class MyFragment {
private MyStringListener listener;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener = (MyStringListener) activity;
} catch (ClassCastException castException) {
/** The activity does not implement the listener. */
}
}
public interface MyStringListener{
public Integer computeSomething(String myString);
}
}
public class MyActivity extends FragmentActivity implements MyStringListener{
@Override
public Integer computeSomething(String myString){
/** Do something with the string and return your Integer instead of 0 **/
return 0;
}
}
@try-no-cry
Copy link

it returns null on the object

@bentley-maker
Copy link

me too,

@brij21141
Copy link

mee too

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment