Skip to content

Instantly share code, notes, and snippets.

@StevenByle
Last active March 24, 2019 07:34
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 StevenByle/5729698 to your computer and use it in GitHub Desktop.
Save StevenByle/5729698 to your computer and use it in GitHub Desktop.
Android: Example Fragment communication via interfaces with parents, and informing children Fragments of updates depending on their state.
@Override
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