How to format code in Android Studio (IntelliJ IDEA)

Solution 1:

Just right-click on the project or directory, and select Reformat Code Reformat Code

Solution 2:

If you want to:

  1. Order/FormatCode: Ctrl + Alt + L
  2. Implement Methods: Ctrl + I
  3. Override Methods: Ctrl + O

There isn't any need for them to be capital letters. This is just for the example.

Solution 3:

First you will need to configure how your code is formatted. This can be done by going to

[Main Menu] -> File -> Settings
then go to
(Project Settings) -> Code Style -> Java

In this area you can define all the formatting rules that you would like to apply to your code.

Now you should check (or change) the keyboard shortcut for reformatting code by going to

[Main Menu] -> File -> Settings
then go to
(IDE Settings) -> Keymap

Just type Reformat Code into the search box at the top right to find it.

Once this is done, highlight the code you want to reformat and use the keyboard shortcut to reformat your code based on the rules you defined.

Solution 4:

In Android Studio (on the Mac), I select the code chunk, and then select the Code menu item and click Auto-Indent Lines.

See screenshot:

Enter image description here

Shortcut key (on Mac) is Ctrl + Alt + I.

Solution 5:

At least on my Android Studio version, "keep when formatting - line breaks" was enabled by default. So you need to go to

PreferencesEditorCode StyleJava and disable that checkbox (see the below screenshot).

Android Studio Preferences