简体   繁体   中英

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, ...) )? 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.

Method I use (a little more drawn out and probably not the best of the two):

In each class, make a private Context mContext;
Then, in the onCreate() of each class, make mContext = this;
Finally, replace SomeClass.this in your Intent with mContext .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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