You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio重构包名后Java生成文件报错,新手求助

Fixing Package Refactoring Issues in Android Studio (For Beginners)

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:

  1. 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 select Refactor > 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.
  2. 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 Project to delete all old generated files. Then run Build > Rebuild Project—this will regenerate the files using your new package name automatically.
  3. Double-Check Your AndroidManifest.xml

    • Open your AndroidManifest.xml file and confirm the package attribute at the top matches your new package name. Sometimes manual folder renaming doesn’t update this, which causes lingering issues.
  4. 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 for Invalidate and Restart, and let the IDE restart. This clears stale index data that could be causing conflicts.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 09:47:41