In some cases, fragment and activity sharing events may be required. Defining a callback interface within fragment is a good method and requires that the callback method be implemented by the activity holding it. When an activity receives a callback through an interface, it can share information with other fragment in the layout if necessary.
For example, if the app of a music player has two fragment items in one activity, one for displaying the fragment list (fragment a) and the other for displaying the fragment B ), fragment a must tell activity when the list item is selected so that it can tell fragment B to display the corresponding song information. In the following example, the onmp3changedlistener interface is declared in fragment.
Public static class fragmenta extends listfragment {... // The activity holding it must implement this callback method public interface onmp3changedlistener {public void onmp3changed (INT index); // index indicates the sequence number of the song in the list }...}
Then, the activity holding this fragment must implement the onmp3changedlistener interface, and rewrite the onmp3changed () method to notify fragment B of the event from fragment. Make sure that the activity holding fragment implements this interface. The onattach () callback method of fragment A (the system calls this method when fragment is added to the activity) is converted to onattach () by the type conversion method () the input activity is used to instantiate an onmp3changedlistener instance.
public static class FragmentA extends ListFragment { onMp3ChangedListener mListener; ... @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (onMp3ChangedListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener"); } ...}
If this activity does not implement this interface, fragment will throw a classcastexception.
If successful, the mlistener member will have reference to the onmp3changedlistener object implemented by the activity, so that fragment A can define the callback method and activity sharing event through the onmp3changedlistener interface. For example, fragment
A inherits the listfragment. Every time you click a list item, the system calls the onlistitemclick () method in fragment, and then calls the onmp3changed () method and the activity sharing event:
public static class FragmentA extends ListFragment { OnArticleSelectedListener mListener; ... @Override public void onListItemClick(ListView l, View v, int position, long id) { mListener.onMp3Changed(position); } ...}
The position parameter passed to onlistitemclick () is the row ID of the clicked item. Activity (or other fragment) uses this ID to obtain the corresponding song information from the song list.