Last active
March 31, 2022 07:15
-
-
Save mstfldmr/fc4fa436f2e553b10865 to your computer and use it in GitHub Desktop.
Calling Fragment method from Activity / Activity method from Fragment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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; | |
} | |
} |
me too,
mee too
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it returns null on the object