[英]How can one get reference to the outer class from inner class not using outer class name?
Here is the sample code: 以下是示例代码:
Class SomeClass extends Activity {
public void someMethod() {
Runnable r = new Runnable() {
public void run() {
Intent service = new Intent(SomeClass.this, SomeOtherClass.class);
// ...
}
}
}
}
How can I change the code to not use SomeClass
( in new Intent(SomeClass.this, ...)
)? 如何更改代码以不使用
SomeClass
(在new Intent(SomeClass.this, ...)
)? I want to place this sample in multiple classes and I do not want each time use different class name. 我想将此示例放在多个类中,我不希望每次都使用不同的类名。
Shorter method (suggested): 更短的方法(建议):
Replacing SomeClass.this
in your Intent with getApplicationContext()
should do the trick. 用
getApplicationContext()
替换你的Intent中的SomeClass.this
应该可以解决问题。
Method I use (a little more drawn out and probably not the best of the two): 我使用的方法(稍微抽出一点,可能不是两者中最好的):
In each class, make a private Context mContext;
在每个类中,创建一个
private Context mContext;
Then, in the onCreate()
of each class, make mContext = this;
然后,在每个类的
onCreate()
中,make mContext = this;
Finally, replace SomeClass.this
in your Intent with mContext
. 最后,用
mContext
替换你的Intent中的SomeClass.this
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.