Java – Android – why is using interfaces considered a best practice for communicating between activities and fragments?

In this document "communicating with other fragments", Google tells us that the best practice for transmitting activity and fragment is to implement an interface This interface can then be called by the fragment and perform the necessary actions in the activity

But there is also a way for hackers to do this Get the activity directly through the method "getactivity()", and then we can use all the "public methods" below it

This puzzles me Because I can't think of any key disadvantages of using hackers to do any of this

The advantages of the first method that came to my mind are:

>I can restrict resource accessibility under my activities However, because fragment can call "getactivity()", it can actually access all "public" methods So it doesn't convince me. > The code is more readable and storytelling Using the first method, the code tells us that "this activity only opens these specific accessible areas of the fragment." By looking at the code in the activity, we can directly know that "the internal part of the fragment may interfere with the content of the activity" Otherwise, we need to open the code under fragment to see its function

Well, after I've summed up all this, I'm a little convinced of myself But frankly, I really want something else solid, and there must be a reason to do so Any ideas or documents will be greatly appreciated!!

Solution

Most importantly, the main advantage is the modularity of the code When you call the parent class directly from the child class, create a cyclic dependency This actually means that you cannot replace one without changing the other This approach often makes spaghetti code difficult to maintain, or even more difficult to extend, and it is almost impossible to replace without major refactoring efforts

As for your example: if you call the public method of your activity directly from the fragment, you will not be able to reuse your fragment in other activities without implementing the Hacky solution (such as if (getactivity () instanceof a) {...} Else {...}), nor can you replace your activities, such as the controller class, or any other solution you propose

If you have difficulty understanding this topic, I strongly recommend that you read this book effective Java

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