Solution to the problem of nested fragments in Android

It is said that fragment is easy to use. Duang ~ ~, I have a problem again. Record it and share it with the students who encounter this problem! 1. Getactivity() is null when nesting fragments

Activity a nested fragment B, B nested fragment C, C jumps to activity D. when activity D is finished, getactivity is easy to be empty in C. If your activity is recycled, you need to save the fragment information in the bundle. My solution: after fragment instantiation, you will register in the fragment manager of the activity. This action is encapsulated in onattach in the fragment In the (activity activity) method, you can directly assign values in the onattach (activity) method

2. When a fragment is nested in a fragment, the onactivityresult method of the child fragment is not executed. Activity a is nested in fragment B, and C jumps to activity D through startactivityforresult. In fact, not everyone will encounter this problem. This problem may not occur when your activity a and fragment B do not rewrite the onactivityresult method, However, my activity a rewrites the onactivityresult method, so when activity D is destroyed, I directly execute the onactivityresult of the activity. In fact, this problem is also very simple, but I may not think of it when I encounter it. The solution is to add super.onactivityresult (requestcode, resultcode, data) to the onactivityresult method in the activity; Everything is OK. The onactivityresult method of activity:

Onactivityresult method of fragment:

Of course, in some special cases, don't go through the onactivityresult method. Don't be upset when you encounter it. Manually call the fragment method from the onactivityresult method in the activity and pass the corresponding data. If you have a better method, communicate with each other!

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
分享
二维码
< <上一篇
下一篇>>