Reputation: 303
I'm using onBackPressed() method in my app in few places. In every place I want this method to do other stuff. When user is in X layout I want to Back button does somethink else than in Y layout, so I'm thinking that the best solution would be to use arguments in onBackPressed method. For example in X onBackPressed(0); and in Y onBackPressed(1); etc.
@Override
public void onBackPressed(int c){
if(c==0)Toast.makeText(getApplicationContext(), "This is X", Toast.LENGTH_SHORT).show();
if (c==1)Toast.makeText(getApplicationContext(), "This is Y", Toast.LENGTH_SHORT).show();
}
But it does not work. Do You have any ideas what can I do to make it work ? Or is there any better solution for this problem?
Upvotes: 2
Views: 2357
Reputation: 11608
you are overriding a framework method and you can't pass it any other parameters than those defined by the API. However you can create an own method to check what you need like:
@Override
public void onBackPressed(){
switch(checkLayout()){
case 1: //do stuff
break;
case 2: .....
}
}
And to extend CommonsWare's comment a little: yes, users are not "in a certain layout". Users are interacting with a certain Activity
that is hosting a certain layout. If you don't really understand what this means, you should probably consult this document: http://developer.android.com/reference/android/app/Activity.html
Upvotes: 2
Reputation: 3229
The way overriding methods in Android works is that you must exactly duplicate the method header. When you change it, it will still compile, but Java will read it as an overloaded method and thus not do anything with it because it is never called.
You would be a lot better off handling an instance variable outside of onBackPressed() and then handling it when it's actually pressed.
The following is a simple implementation.
//Your instance variable
boolean myRandomInstanceVariable = true;
@Override
public void onBackPressed()
{
if(myRandomInstanceVariable)
{
//do stuff
}
else
{
//do other stuff
}
}
Upvotes: 2
Reputation: 48252
Create a field in your class set it to some value in some place to some other value in some other place. Then in onBackPressed()
check that field's value and proceed accordingly.
Upvotes: 0