In this post we will add some guidelines to our Java code editor which will be suitable for contributing to the AOSP (Android Open Source Project) as described in the following link.
link:
Android Code Style
To format your Java code, and organize your imported packages, you will need the following two files:
Android Formatting link:
android-formatting.xml
Android Import Order link:
android.importorder
Copy and paste the respective contents of each link into separate files. Be sure to preserve the file extension; ".xml" and ".importorder" respectively.
The code below shows a comparison between the default Java formatted code, and code formatted for Android.
/**
* A sample source file for the code formatter preview
*/
package mypackage;
import java.util.LinkedList;
public class MyIntStack {
private final LinkedList fStack;
public MyIntStack() {
fStack = new LinkedList();
}
public int pop() {
return ((Integer) fStack.removeFirst()).intValue();
}
public void push(int elem) {
fStack.addFirst(new Integer(elem));
}
public boolean isEmpty() {
return fStack.isEmpty();
}
}
Default Java format
/**
* A sample source file for the code formatter preview
*/
package mypackage;
import java.util.LinkedList;
public class MyIntStack {
private final LinkedList fStack;
public MyIntStack() {
fStack = new LinkedList();
}
public int pop() {
return ((Integer) fStack.removeFirst()).intValue();
}
public void push(int elem) {
fStack.addFirst(new Integer(elem));
}
public boolean isEmpty() {
return fStack.isEmpty();
}
}
Android format
To import a new format:
- Go to Eclipse and navigate to Window-> Preferences
- Next, expand the Java section, then expand the Code Style section
- Next, select the Formatter section, and import the android-formatting.xml file
Similarly here is a comparison between the import order for packages:
 |
| Java import order |
 |
| Android import order |
- Go to Eclipse and navigate to Window-> Preferences
- Next, expand the Java section, then expand the Code Style section
- Next, select the Organize imports section, and import the android.importorder file
Once each file is imported your Android workspace will format your code and be suitable for contribution to the AOSP.