Starting an Android Activity from an Listener defined in an external class file
I have an Activity MyActivity
with a Button MyButton
.
I want to attach a MySpecialOnClickListener
to MyButton
.
I write MySpecialOnClickListener
in an external class file.
public class MySpecialOnClickListener extends ButtonHandler implements OnClickListener {
public OnClickListenerWithSpeech (Context context)
{ super.context = context; }
@Override
public void onClick(View view) { handleClick(view); }
}
and ButtonHandler looks like this
public abstract class ButtonHandler {
protected Context context;
protected void handleClick (View view){
if (view.getid()==R.id.button_B) {
context.startActivity (new Intent(context, ActivityC.class));
}
}
}
I basically want to store all logic for Buttons in the ButtonHandler.
SO...as I said, I have the MySpecialOnClickListener
defined in an external class file.
When I click MyButton
I get the following fatal error.
Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
So I can't start an activity normally from within a non-Activity. Fair enough.
However, if I change MySpecialOnClickListener
to be an inner class in 'MyActivity' it works fine. Remember 'ButtonHandler' is still an external class file. So it (where ActivityC
is ultimately started from) doesn't change.
My question (finally) is: can someone explain the logic of why one is allowed and the other isn't. I presume its a scoping thing or something but I'm a bit confused. It seems the code to start the process of starting an activity has to literally be inside another Activity.
EDIT - PROBLEM SOLVED
See below. The location of the class is irrelevant. I just开发者_StackOverflow社区 didn't pass in the context properly.
because the ButtonHandler 'context' field isn´t associated with any activity context. So, when you attach the MySpecialOnClickListener instance to a button you create it passing the context parametener, isn´t???
something like this:
MySpecialOnClickListener listener = new MySpecialOnClickListener(MyActivity.this);
aButton.setOnClickListener( listener );
in this way you´re constructing the Button with the correct context...
It's likely that you are not passing the Activity context to MySpecialOnClickListener. Could you show me the difference in the way you invoke the inner-class approach?
Apologies to those of you who tried to answer. It was my fault (and I didn't include the following info initially for people)
When I was passing in the context to the 'MySpecialOnClickListener' I would do:
view.setOnClickListener(new MySpecialOnClickListener(getApplicationContext()));
when I should have done:
view.setOnClickListener(new MySpecialOnClickListener(this));
So getApplicationContext()
doesn't seem to get the "correct" context for the app.
Which leads me to my next question as to what getApplicationContext()
actually returns :)
精彩评论