例如,Android Studio提供了强大的重构功能Rename。我可以使用它来更改变量,字段,参数的名称,但是我似乎找不到找到重命名类型的方法。例如:
LinearLayout layout = (LinearLayout) v.findViewById(....);
// ........
// A bunch of code using `layout` many times
我怎样才能快速重构LinearLayout
来RelativeLayout
,并将它应用到代码太多的休息吗?我可以为字段做同样的事情吗?
您正在寻找的功能是Type Migration!
阿Type Migration可以通过右击上的变量或字段,然后选择的类型来执行Refactor- > Type Migration。或者,您可以使用以下键盘快捷键:
只需选择要迁移到的类型,单击“重构”,Android Studio就开始发挥其魔力!
您似乎误会了Rename实际的情况。
Rename可用于从字面上重命名元素。因此,您可以使用它来更改变量,参数,方法或类的名称。例如,如果您有一个名为的类,Foo
并且想要将其更改为Bar
,则可以使用轻松实现Rename。
但是您不能重命名,LinearLayout
因为它是框架类,并且当然不能修改。但是,这根本不应该成为问题,因为您实际上并不想重命名LinearLayout
,是吗?您实际要做的是将类型从更改LinearLayout
为RelativeLayout
。另外还有一个非常有用的重构功能,称为Type Migration。
您可以Type Migration通过右键单击要交换其类型的任何变量,然后选择Refactor->来执行Type Migration。之后,会弹出一个对话框,您可以输入要迁移到的类型RelativeLayout
。然后只需单击Refactor
,Android Studio就开始发挥其魔力。可能会有一个额外的弹出窗口,通知您代码中所有无法自动迁移的内容。只需浏览冲突列表,完成后点击Ignore并手动修复这些冲突。
这是Type Migration工作的例子。我从以下代码开始:
private LinearLayout mLayout;
private void doStuff(ViewGroup container) {
LinearLayout layout = (LinearLayout) container.findViewById(0);
layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
...
}
});
mLayout = layout;
fooTheBar(layout);
}
private void fooTheBar(LinearLayout layout) {
...
}
现在我执行Type Migration到RelativeLayout
的局部变量layout
在doStuff()
。结果看起来像这样:
private RelativeLayout mLayout;
private void doStuff(ViewGroup container) {
// Here is the only conflict which could not be refactored automatically.
// I had to change the cast to RelativeLayout manually.
RelativeLayout layout = (LinearLayout) container.findViewById(R.id.linearLayout);
layout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
...
}
});
mLayout = layout;
fooTheBar(layout);
}
private void fooTheBar(RelativeLayout layout) {
...
}
如您所见,您Type Migration做了出色的工作。字段的类型,甚至参数的类型fooTheBar()
都更改为RelativeLayout
。只有一次冲突。Android Studio无法在的最顶部自动更改演员类型doStuff()
。我不得不手动修复。如前所述,在执行重构时,我曾被警告有关此冲突。
您当然可以问自己,为什么它可以自动更改字段的类型和参数,却不能更改强制类型的转换,但是如果您考虑一下,这实际上很有意义:
无法自动迁移的代码部分为(LinearLayout) container.findViewById(R.id.linearLayout)
。当然,此方法会查找View
带有id的R.id.linearLayout
。这View
可以在布局xml中定义,也可以container
在运行时动态添加到其中,但是在任何情况下,都不能自动重构它而不会破坏功能。只有开发人员才能决定如何处理,这就是为什么要警告您的原因。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句