如何在基于IntelliJ IDEA的新IDE Android Studio中重命名软件包?

是否包含自动重构?

我想进行大规模重构,但我不知道怎么做。我在Eclipse工作了两年,在Eclipse中它是一个一键操作。


当前回答

ctrl+Shift+R一直对我有效。只需替换所有文件并选择所有文件。

其他回答

按Ctrl+Shift+R用新包装替换旧包装。右键单击程序包名称。重构>重命名并重命名为新的

这对我来说非常有效,即使是更改所有相关模块中的引用,也可以更改我想在包中修改的文件夹名称,但对我来说,只有完全按照以下步骤操作,这才有效:

A-如果您想更改根文件夹的名称(换句话说,通常在包中用于包含主要活动的文件夹的名称),可以在以下步骤(B到C)之前或之后通过退出“Android Studio”手动重命名此根文件夹。单击“导入项目…”,然后单击项目的新名称(此导入过程将自动使用项目文件重新调整“Gradle”文件)B-在接下来的C步骤之前,不要忘记手动修改要在包中更改的文件夹名称,方法是在以下3个文件中更改它们:“AndroidManifest.xml”、“MainActivity.java”(或您最终为第一个活动选择的名称)和“build.gradle(Module:app)”文件。C-按照上述步骤1至6(“在项目窗格中,单击小齿轮图标…”)->https://stackoverflow.com/a/29092698/2001610 D-仅当您现在想要更改根文件夹的名称时,您可以按照上面所述的“A”过程进行操作。

接受的答案对我不起作用。这里有一个python脚本,可以直接在源文件上更改包名。

"""
Notes:
1 - This script it for python3
2 - Create a backup first
3 - Place on the root folder of the android project you want to change
4 - run `python change_android_studio_pkg_name.py`
5 - Type the old package name
6 - Type the new package name
7 - Clean and Rebuild on Android Studio
8 - SRC folder names won't be changed but app will work
"""

import os, glob, traceback
from pathlib import Path

def rwf(fp, mode="r", data="" ):
    if mode == "r":
        with open(fp, "r", encoding='utf8') as f:
            return(f.read())
    elif mode == "w":
        with open(fp, "w", encoding='utf8') as f:
            f.write(data)

old_pkg = input("Old PKG\n").strip()
new_pkg = input("New PKG\n").strip()

if not old_pkg or not new_pkg:
    exit("Args Missing")

dirname, filename = os.path.split(os.path.abspath(__file__))
file_types = ['xml', 'txt', 'json', 'gradle', 'java']
_fs =  glob.iglob(f"{dirname}/**", recursive=True)
for file_path in _fs:
    ext = Path(file_path).suffix.replace(".", "").lower()
    if os.path.isfile(file_path) and ext in file_types:
        try:
            content = rwf(file_path)
            new_content = content.replace(old_pkg, new_pkg)
            rwf(file_path, "w", new_content)
        except:
            print(traceback.format_exc())
            pass

蟒蛇3要点

右键单击package->refactor并更改名称。

您也可以在清单中更改它。有时,如果您更改包名,但在创建.apk文件后,它会显示不同的包名。此时,检查build.gradle文件中的“applicationId”。

选择要重构的包。重构(Refactor)→ 移动→ “将xxx移动到新包”。