Most of the time, our activity takes control and view functions, making the activity class more and more large, forming the last activity that cannot be maintained. How to optimize Android code, you can perform the following steps in sequence:
1. Division of Duties
First, we consider activity as a view, and since it is view, it should be more responsible for the view, and as far as possible not to deal with control-related things.
Pages like network access, database data acquisition, and so on, are moved to another class to do, this class to do these things, through handler or listening to notify the Activity Update page, and no longer the activity to execute the logic.
2. Page chunking
An activity, it is impossible that all of its components need to communicate closely with each other, we first separate the pieces of each other. A change from a to a a,b,c;
Then for a only need to instantiate a,b,c, management a,b,c between the interaction, and by A,b,c himself to manage their own logic.
3. Independence
Custom view, to simplify the comparison of independent a logic, since there is no interaction between a and other b,c, or very little interaction, then it can itself become a separate view, to manage their own logic. Where it needs to be, it just needs to be instantiated.
4. Cross
The most headache is that a some logic belongs to their own, but it has frequent and b,c interaction. In this case, we create a new control A, which gets the reference to this a, which deals with a separate part of the view, while the intersecting logic remains at the highest level.
For example, one of my pages, with Avatar, name, Avatar and name also have some interaction, such as point Avatar, appear hello+name, the following list shows some configuration, avatar and name is network acquisition, configuration is local access;
Then we can divide it into a avatar and a name, B config area
A and B basic no interaction
Then a is defined as a custom view
b Define a control to manage the view
Define c to get network information
Define d to get local data
A provides a way to get the data, refresh the page
b provide a method to get the data, refresh the page
In activity, as long as the instantiation can
Android also has MVP mode, can also be combined with the above integrated use
Keep the beauty value of the code ...
Of course necessary appropriate comments, but the method is big, these are not just Android
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Some thoughts on keeping Android code Yan value