Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert tabs to spaces and auto formatting on save in android studio

I would like know the steps for converting tabs to 4 spaces and auto formatting the java code on Save which is similar to eclipse.

In Eclipse I used to do the settings

For Converting tabs to Spaces I used to do the below setting

Open references-> Java->Code style -> Formatter->Create a new profile-> Change the setting from tabs only to Spaces only

To format the entire Java code of that particular file on save I used to do the below settings in Eclipse

Open preferences-> Java -> Editor -> Save Actions->Check the appropriate options in the dialog

But I don't aware to do the similar settings in Android Studio, can anyone help me to setup this. Thanks in advance.

like image 752
Bethan Avatar asked Oct 18 '16 07:10

Bethan


1 Answers

For Auto Formatting your Java/xml files in Android Studio use following commands:

CTRL + ALT + L

If you are using ubuntu , using this command will Log you out, use :

Shift + CTRL + ALT + L

A popUp will appear : select whole file and Rearrange code and You are done. :)

Update :

As you are looking for a single point to go with your work as eclipse did, there is no such built in functionality in Android studio but it gives you the ability to do it through Macro, Follow these steps:

  1. In studio open any of your source code file.
  2. Press Ctrl + Alt + O This is used to find/optimize unused import. If a dialog open select 'Dont show it again' and hit Run.
  3. Go to Edit > Macros > Start Macro Recording.
  4. Press Ctrl + Alt + O.
  5. Press Ctrl + Alt + L. This formats your code. (Shift+ctrl+Alt+L for ubuntu).
  6. Press Ctrl + S ,This saves your file;)
  7. Go to Edit > Macros > Stop Macro Recording.
  8. Save this created macro with name for instance:“Auto Formatting".

Boom, You have now successfully created your Macro, Now just add/assign a shortcut to it:

  1. Open Preferences.
  2. Search in the left bar for Keymap.
  3. In the right hand pane, click in the search bar and type the name of your saved macro("Auto Formatting".)
  4. Double click on your item. There might be two, it doesn’t matter which one you click on.
  5. Click Add Keyboard Shortcut.
  6. Set your keyboard shortcut to Ctrl + S.
  7. Finally,Confirm overriding Ctrl + S to be your new macro.

That's it! your done man. Cheers :)

like image 68
Anurag Avatar answered Oct 19 '22 03:10

Anurag