简体   繁体   English

如何从不使用外部类名的内部类中获取外部类的引用?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM