When you do native Android development, you use import
statements. A lot of import
statements. Even the “Hello World”-ish template app that Android Studio generates when you select Empty Compose Activity contains 11 import
statements:
Worse still, you end up adding more import
statements over time, as you add more code. It’s easy to end up with a screenful or more of import
statements, which makes them more difficult to manage.
How I used to sort import
s in Android Studio
I used to keep import
statements organized by occasionally rearranging them into alphabetical order by hand. This soon became annoying, so I automated the process with a simple Jupyter Notebook. Using this Notebook, I’d copy the import
statements…
…and then paste them into a variable, which would then be processed with a Python one-liner:
# Python
print('\n'.join(sorted(import_lines.splitlines())))
Here’s screenshot showing how I last used my import
-organizing Jupyter Notebook:
After running it, I’d copy the one-liner’s output and paste it back into my Android code. Problem solved!
How to sort import
s in Android Studio
I’ve only recently found out about the Optimize Imports option in Android Studio (and many other JetBrains IDEs), and it does a better job that my Jupyter Notebook, which simply puts the imports in alphabetical order. It also:
- Deletes duplicate
import
lines (I should update my script to do the same), and - consolidates
import
s when possible.