How to convert tabs to spaces and format them automatically when saved in Android Studio
I would like to know the steps to convert tabs to 4 spaces and automatically format java code on save, which is similar to eclipse.
I used to do the setup in Eclipse
In order to convert tabs to spaces, I used to do the following settings
Open references-> Java->Code style -> Formatter->Create a new profile-> Change the setting from tabs only to Spaces only
In order to format the entire Java code of that particular file on save, I used to make the following settings in Eclipse
Open preferences->Java-> Editor -> Save Actions-> check the appropriate option in the dialog box
But I don’t know to do a similar setup in Android Studio, can anyone help me set it up.
Thanks in advance.
Solution
To automatically format your Java/xml file in Android Studio, use the following command:
CTRL + ALT + L
If you are using Ubuntu and using this command will log you out, use:
Shift + CTRL + ALT + L
A pop-up window will appear: select the entire file and rearrange the code, and you’re done. 🙂
Update:
When you’re looking for a single point to get your work done like eclipse
, there’s no such built-in feature in Android studio
, but it enables you to do it with Macro
, follow these steps:
- Open any of your source code files in Studio.
- Press
Ctrl + Alt + O
This is used to find/optimize unused imports. If the dialog box opens, select Don’t show again and click Run. - Go to Edit> Macros> Start Macro Recording.
- Press
Ctrl + Alt + O
. - Press
Ctrl + Alt + L
. This formats your code. (Shift+ctrl+Alt+L
for ubuntu). - Press
Ctrl + S
, which will save your file; ) - Go to Edit> Macros > Stop Macro Recording.
- Save the created macro with a name, for example: “Auto Format”.
Boom, you have now successfully created your macro, now just add/assign a shortcut to it:
- Open Preferences.
- Search for Keyboard Mapping in the left sidebar.
- In the Pane on the right, click the search bar and type the name of the macro you saved (Automatic Formatting). )
- Double-click your project. There may be two, it doesn’t matter which one you click.
- Click Add keyboard shortcut.
- Set the keyboard shortcut to
Ctrl + S
. - Finally, confirm that Overriding
Ctrl + S
becomes your new macro.
That’s it! You’re. Cheers 🙂