2

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?

2
  • Users are not "in" a "layout". Commented Nov 5, 2013 at 21:18
  • there is no argument to onBackPressed. If you change that, you are not overriding this method. beside, how would you seriously expect a system to give you a value for c when it has never ever ever ever heard of it before (ever) and has no idea what it is supposed to represent ?
    – njzk2
    Commented Nov 5, 2013 at 21:29

3 Answers 3

2

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

0
2

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
   }
}
0

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.