我是Android的新手,我想知道Fragment clases中的getActivity()
和this.getActivity()
之间是否有区别。例如,我们在单一类中有一个方法(不扩展Activity或Fragment),例如:
public static void method(Context context){
... some code
}
如果要使用它,只需在片段类中调用它:
MyMethodClass.method(getActivity());
或
MyMethodClass.method(this.getActivity());
我知道两者都在工作,但是我需要专业意见。
谢谢。
它们是相同的。 this关键字引用当前对象。
public class Car {
int speed = 10;
public void move() {
//using this.speed or speed makes no difference here
}
}
如果从Fragment
扩展,则getActivity()
和this.getActivity()
都将调用Fragment#getActivity(),因此正如其他人所说,这没有什么区别。两者都将在父类中查找方法。一个小小的更正:您提供的示例代码:
MyMethodClass.method(getActivity());
如果method()
是静态方法,则将起作用。否则,您应该这样称呼它:
MyMethodClass.this.method(getActivity());
但是那只是基本的Java;)
使用getActivity()关键字而不是“片段”中的“ this”关键字