How to create common code for parts of an Android activity?

My application has 14 activities. From this step 9, the custom title bar and tab bar. so here I need to write this common code in one place instead of redundant code in every action that contains a custom title bar and tab bar code (for example, a layout and its code specific to a specific activity).

What are the possible ways to do this?

+8
android android-activity
source share
2 answers

General way:

  • Create a superclass called, for example, CommonActivity that extends Activity
  • Put the template code inside this class
  • Then make your actions extend with CommonActivity instead of Activity :

Here is a simple example:

 public class CommonActivity extends Activity{ public void onCreate(Bundle b){ super.onCreate(b); // code that is repeated } protected void moreRepeatitiveCode(){ } } 

And your current actions:

 public class AnActivity extends CommonActivity{ public void onCreate(Bundle b){ super.onCreate(b); // specific code } } 
+11
source share

Hmm .. The general code does not always have to be in the Activity class, but just in the regular class. What could we call these methods according to our needs, referring to a common code class.

Am I right with this example ?

Of course, if we need this as an Activity, the above sentence will work fine if we take care of the Activity life cycle and we don't forget to add it to the manifest file .

In general, Activities should simply create a user interface, handle events, and delegate business logic and / or other actions to other components of our application.

Greetings

+1
source share

All Articles