Detailed explanation of communication between fragment and activity in Android

Detailed explanation of communication between fragment and activity in Android

Communicate with activity

Although the implementation of fragment is independent of activities and can be used for multiple activities, each activity contains different instances of the same fragment. Fragment can call getactivity () method to easily get the object of its activity, and then find the controls in the activity (findviewbyid()).

For example:

Similarly, an activity can find the frames it contains through the fragmentmanager method.

For example:

Activity responds to the event of the fragment

Sometimes, you may need fragments to share events with activities. A good idea is to define a callback interface in the fragment and then implement it in the activity. For example, the news program has an activity that contains two fragments. Fragment a displays the news title and fragment B displays the content corresponding to the title. Fragment a must tell activity when the user selects a title, and then activity tells fragment B, and fragment B will display the corresponding content (why is it so troublesome? Just tell fragmenta to fragmentb directly? It's OK, but your fragment reduces the reusability. Now I just need to tell my event to the host and let the host decide how to deal with it. Is this better for reusability?) for example, onarticleselectedlistener interface

Define in fragmenta:

Then, the activity implements the interface onarticleselectedlistener and notifies fragmentb in the method onarticleselected(). When a fragment is added to an activity, the fragment method onattach () will be called. This method is suitable for checking whether the activity implements the onarticleselectedlistener interface. The checking method is to type convert the instance of the incoming activity,

As follows:

If the activity does not implement that interface, the fragment throws a ClassCastException exception. If successful, the mlistener member variable holds an instance of onarticleselectedlistener. Fragment a can then call the method of mlistener to share events with the activity. For example, if fragmentA is a ListFragment, every time you select a list, you call the onListItemClick () method of fragmentA, calling onArticleSelected () in this method to share events with activity, as follows:

The parameter ID passed in by onlistitemclick() is the ID of the selected row of the list. Another fragment uses this ID to get the content of the title from the ContentProvider of the program.

If you have any questions, please leave a message or go to the community of this site for exchange and discussion. Thank you for reading. I hope it can help you. Thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>