繁体   English   中英

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

[英]How can one get reference to the outer class from inner class not using outer class name?

以下是示例代码:

Class SomeClass extends Activity {
    public void someMethod() {
        Runnable r = new Runnable() {
            public void run() {
                Intent service = new Intent(SomeClass.this, SomeOtherClass.class);
                // ...
            }
        }
    }
}

如何更改代码以不使用SomeClass (在new Intent(SomeClass.this, ...) )? 我想将此示例放在多个类中,我不希望每次都使用不同的类名。

更短的方法(建议):

getApplicationContext()替换你的Intent中的SomeClass.this应该可以解决问题。

我使用的方法(稍微抽出一点,可能不是两者中最好的):

在每个类中,创建一个private Context mContext;
然后,在每个类的onCreate()中,make mContext = this;
最后,用mContext替换你的Intent中的SomeClass.this

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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