Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Android: Example Fragment communication via interfaces with parents, and informing children Fragments of updates depending on their state.
public void onImageSelected(ImageItem imageItem, int position) {
// Only inform the other fragments if the selected position is new
if (mCurImagePosition != position) {
Log.d(TAG, "onImageSelected: title = " + imageItem.getTitle() + " position = " + position);
// Keep track of the selected image
mCurImageResourceId = imageItem.getImageResId();
mCurImagePosition = position;
// Get the fragment manager for this fragment's children
FragmentManager fragmentManager = getChildFragmentManager();
ImageListFragment imageListFragment = (ImageListFragment) fragmentManager.findFragmentByTag(ImageListFragment.class.getName());
ImagePagerFragment imagePagerFragment = (ImagePagerFragment) fragmentManager.findFragmentByTag(ImagePagerFragment.class.getName());
// If the fragments are in the current layout, have them select the
// current image
if (imageListFragment != null) {
imageListFragment.setImageSelected(imageItem, position);
if (imagePagerFragment != null) {
imagePagerFragment.setImageSelected(imageItem, position);
// Notify the parent listener that an image was selected
if (mParentOnImageSelectedListener != null) {
mParentOnImageSelectedListener.onImageSelected(imageItem, position);
public interface OnImageSelectedListener {
* Inform the listener that an image has been selected.
* @param imageItem
* @param position
public void onImageSelected(ImageItem imageItem, int position);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.