Java – How to convert tabs to spaces and format them automatically when saved in Android Studio

How to convert tabs to spaces and format them automatically when saved in Android Studio… here is a solution to the problem.

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:

  1. Open any of your source code files in Studio.
  2. 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.
  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, which will save your file; )
  7. Go to Edit> Macros > Stop Macro Recording.
  8. 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:

  1. Open Preferences.
  2. Search for Keyboard Mapping in the left sidebar.
  3. In the Pane on the right, click the search bar and type the name of the macro you saved (Automatic Formatting). )
  4. Double-click your project. There may be two, it doesn’t matter which one you click.
  5. Click Add keyboard shortcut.
  6. Set the keyboard shortcut to Ctrl + S.
  7. Finally, confirm that Overriding Ctrl + S becomes your new macro.

That’s it! You’re. Cheers 🙂

Related Problems and Solutions