What's that “MainActivity.this is not enclosing class” error actually?

后端 未结 1 932
执念已碎
执念已碎 2020-12-31 09:38

I\'m having problem in executing the following code.

Actually I wanted to use an image as a link to another page or activity. How it\'s done

and

wh

1条回答
  •  一整个雨季
    2020-12-31 10:08

    An enclosing class is exactly what it sounds like - it's a class that encloses (not inherits) the class at the given statement. In order to reference the enclosing class instance, the this keyword must be prefixed with the class name - hence MainActivity.this.

    class ABC {
        class XYZ extends Activity {
        } 
    }
    

    In the simple example above, ABC is the enclosing class of XYZ.

    Your error is telling you that MainActivity is not an enclosing class at the statement location, and so the this instance of that class cannot be accessed.

    Your MainActivity2 class inherits from MainActivity, but there is no enclosing class at the Intent(...) statement. Since the Intent() constructor requires a Context parameter and your MainActivity2 this instance inherits from Context (Context -> Activity -> MainActivity -> MainActivity2), you can just use this as the parameter:

    So instead of:

     i = new Intent( MainActivity.this, MainActivity2.class); 
    

    use:

     i = new Intent(this, MainActivity2.class); 
    

    0 讨论(0)
提交回复
热议问题