Android Studio重构包名后Java生成文件报错,新手求助
Hey there! I’ve been right where you are—fumbling with manual folder renaming to change a package name, only to end up with broken imports in generated files that won’t stay fixed. Let’s sort this out properly, because manual folder tweaks almost always lead to these messy problems (those generated files are tied to your project’s configuration, not just folder names).
Here’s the step-by-step solution:
Use Android Studio’s Built-in Refactor Tool (Skip Manual Folder Renaming)
- Switch your project view to Project (not the default Android view) using the dropdown at the top-left of the IDE.
- Navigate to
java > [your-old-root-package], right-click the root package folder, and selectRefactor > Rename. - In the popup, choose Rename Package (not Rename Directory), type your new package name, then click
Refactor. - Android Studio will automatically scan and update all references across your project—source code, manifest, gradle files, and more.
Clean & Rebuild to Fix Generated Files
- The
java (generated)directory holds auto-generated code (from tools like data binding, Dagger, or build plugins) that’s tied to your project’s config. Any manual edits you make here will get overwritten on the next build. - To fix broken imports here: Go to
Build > Clean Projectto delete all old generated files. Then runBuild > Rebuild Project—this will regenerate the files using your new package name automatically.
- The
Double-Check Your AndroidManifest.xml
- Open your
AndroidManifest.xmlfile and confirm thepackageattribute at the top matches your new package name. Sometimes manual folder renaming doesn’t update this, which causes lingering issues.
- Open your
Invalidate Caches if Issues Linger
- If you still see weird import errors after the above steps, Android Studio’s cache might be out of sync. Go to
File > Invalidate Caches..., check the box forInvalidate and Restart, and let the IDE restart. This clears stale index data that could be causing conflicts.
- If you still see weird import errors after the above steps, Android Studio’s cache might be out of sync. Go to
Why Manual Folder Renaming Fails:
When you rename folders directly, you only change the file system structure—but Android Studio relies on gradle configurations, the manifest, and its own index to track package names. Generated files are built from these configs, so they’ll keep using the old package name until you properly refactor and rebuild. Any edits you make to generated files get wiped because they’re meant to be auto-generated, not manually modified.
内容的提问来源于stack exchange,提问作者Basit

