Why does startActivity work in one method and fail in another?
I am an android beginner.
I'm struggling to understand why startActivity runs properly when copied from a tutorial I found and fails when I make the smallest change.
Code from the tutorial:
private class ButtonHandler implements View.OnClickListener { public void onClick(View v) { handleButtonClick(); } } private void handleButtonClick() { startActivity(new Intent(this, SecondAct.class)); }
That works. When I try to change it to what I would consider a simpler design, I am getting an error.
private class ButtonHandler implements View.OnClickListener { public void onClick(View v) { startActivity(new Intent(this, SecondAct.class)); } }
The error is:
The constructor Intent(FirstTwoApps.ButtonHandler, Class) is undefined
Notice that all I did 开发者_如何学JAVAwas moved the action from the handleButtonClick()
method to the onClick()
method. Apparently that is not allowed, but I don't understand why.
Any help is greatly appreciated.
You need to change your this
reference to that of the enclosing class, i.e. if your class is named Main
, change it to Main.this
.
Because startActivity
is a method of Context
. In the first example, it is being run from a Context
object, in the second it is being run from a ButtonHandler
object. This is a scoping problem.
The problem is that, handleButtonClick() exists within your Activity class which has context reference to start startActivity() by this.
Now, onClick() exists in ButtonHandler class which has no context scope at all.
So to get context reference from ButtonHandler class you must have to use YouarActivity.this instead this.
Solution -
private class ButtonHandler implements View.OnClickListener {
public void onClick(View v) {
startActivity(new Intent(YouarActivity.this, SecondAct.class));
}
}
精彩评论