Last active
March 24, 2019 07:34
-
-
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.
This file contains 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
@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); | |
} | |
} | |
} |
This file contains 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
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