Android Studio – Reformat code "Optimize imports" order not working properly
When i’m organizing my imports in Android studio (Cmd+Opt+L). I don’t understand how Android Studio define the order.
What I notice is that, imports start with common name like android.*
, java.*
, com.*
, which are grouped alone, separated with a blank line, then all other imports are grouped bellow alphabetically.
In my project, shared with other people, androidx.*
classes are also grouped alone, right after android.*
classes. But in my case, these libraries aren’t sorted alone but put at the end, mixed with all other imports.
Ex:
import android.app.Application; import android.text.TextUtils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.lifecycle.LiveData; import androidx.lifecycle.MediatorLiveData; import com.google.android.exoplayer2.C; import java.util.ArrayList; import java.util.Date; import javax.inject.Inject; // import other classes
Becomes for me after Reformat code :
import android.app.Application; import android.text.TextUtils; import com.google.android.exoplayer2.C; import java.util.ArrayList; import java.util.Date; import javax.inject.Inject; // import other classes + ANDROIDX CLASSES
This is problem, as every time me or a colleague works on a class and use the auto reformat option, git consider it legitimately as change. And sometimes, conflict occurs.
Any idea on how to fix this import order.
Finally found a solution.
The import layout can be modified in settings > Editor > Code Style > Java
. Then in the Imports tab, at the bottom there’s a section for the import Layout !
Si I added a new package bellow android.*
and a blank line.