I thought I had a good grasp of what I was doing but whenever I feel like I have a good handle on something, I'm proven wrong :)
The code in question is this
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mButton = (Button)findViewById(R.id.m_button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
});
}
My confusion is in the new Intent()
and startActivity
method.
I was under the assumption that as long as we're working inside an anonymous class View.OnClickListener
that I'd have to do something like
MainActivity.this.startActivity(intent);
When I'm not inside the anonymous class, I can simply do
new Intent(this,SecondActivity.class);
Can someone explain why I am able to call the startActivity();
method but can't just use this
in the intent parameter?
In the case of the anonymous inner class
this
is the anonymous class itself. To access the outer classthis
from the anonymous one you need to doOuterClassName.this
.However an inner class is allowed to access variables and methods from the outer class. Whether the inner class is anonymous or not makes no difference what-so-ever.
See:
I thought inner classes could access the outer class variables/methods?
Java nested inner class access outer class variables
This is one of the most important differences between static and non-static inner classes.
You only need the class name if (for example) you have a method with the same name in both classes so it call tell which one you mean. That's what is happening with
this
, both the inner and outer class have athis
- so it defaults to the inner one unless you say otherwise.