Android - Parent-Child

> Android

1 - About

A news application can use:

  • one fragment to show a list of articles on the left
  • and another fragment to display an article on the right

both fragments appear in one activity, side by side, and each fragment has its own set of lifecycle callback methods and handle their own user input events. Thus, instead of using one activity to select an article and another activity to read the article, the user can select an article and read it all within the same activity.

3 - Implementation

3.1 - Callback interface

The master/detail interaction is managed through a callback function.

The intern callback interface of the detail fragment that all activities containing this fragment must implement. This mechanism allows activities to be notified of item selections. Example: The MainActivity.java implements implements ForecastFragment.Callback

/* This interface is an inner interface declared in the detailled forecast */
public interface Callback {
	/**
	 * DetailFragmentCallback for when an item has been selected.
	 */
	public void onItemSelected(Uri dateUri);
}
Advertising

3.2 - UI refresh

The child fragment is refreshed through a callback function that signify when the value has changed and restart the loader to refresh the values.

/* In the detail fragment */
void onTriggerChanged( String newValue ) {
	// replace the uri, since the value has changed
	Uri uri = mUri;
	if (null != uri) {
		Uri updatedUri = Contract.Entry.buildUriWithNewValue(newValue);
		mUri = updatedUri;
		getLoaderManager().restartLoader(DETAIL_LOADER, null, this);
	}
}