Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break up an Android activity in multiple files

Tags:

java

android

In Android, a lot of functionality is in the Activity derived class. When an activity gets big (with many event handlers and such), the Java file can get large and very cluttered.

Is there a way to "break up" a Java class code file, like C# has the partial keyword?

like image 287
Bart Friederichs Avatar asked Dec 19 '12 08:12

Bart Friederichs


2 Answers

As others have pointed out, you cannot split the actual file (I view this as a good thing).

You can extract view related functionality in custom views and fragments. Everything else (business logic, Web service access, DB access, etc.) can be in 'helper' classes you use in your activity. Even though activities are the God objects in Android, you don't have to write everything inside the actual activity class. It should only coordinate stuff and implement necessary callbacks and event handlers (which technically can be in their own classes as well).

like image 100
Nikolay Elenkov Avatar answered Oct 04 '22 12:10

Nikolay Elenkov


short answer ? no.

quoted from wikipedia

The Sun Microsystems Java compiler requires that a source file name must match the only public class inside it, while C# allows multiple public classes in the same file, and puts no restrictions on the file name. C# 2.0 and later allows splitting a class definition into several files by using the partial keyword in the source code. In Java, a public class will always be in its own source file. In C#, source code files and logical units separation are not tightly related.

so while you may rework your design and relegate some code to utility classes to unclutter the code, you can not seperate the code of a single class across two files in java.

like image 21
Oren Avatar answered Oct 04 '22 10:10

Oren