Search code examples
javaandroidbuttonback

Android: Implementing a Back Button from a class


Okay, so here is my problem. I'm working on an android app and learning android at the same time, so most of the times I get errors. Normaly I can fix them after researching a bit, but I'm getting stuck in this point.

I'm trying to make a back button for every Activity in my app, so I thought about making a "BackButton" class, so I can instanciate it every time I want to. Here is my BackButton code:

import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.app.Activity;

    public class BackButton extends Activity implements View.OnClickListener{

        public static Button BackButton;

        // Defining the button
        public BackButton() {

            BackButton = (Button) findViewById(R.id.bBack);

            BackButton.setOnClickListener(this);

        }

        //To get the Button
        public static Button getBackButton() {
            return BackButton;
        }


        // OnClickListener
        public void onClick(View v) {

                try {
                    Class MainActivityClass = Class.forName("eu.lafarga.treballderecerca.MainActivity");
                    Intent MainActivityIntent = new Intent(BackButton.this, MainActivityClass); 
                    startActivity(MainActivityIntent);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }finally {
                    // Save the things we've done. 
                }

        }

    }

So, how should I implement this in any activity? I'm doind something wrong? (Sure I'm lol)


Solution

  • Personally, I would suggest not doing this. I think overriding the back button in each Activity would be safer, more flexible, and just as easy, if not easier. Chances are, you aren't always going to want to return to the MainActivity as your app grows because its likely that this won't be the expected action for the users when they hit the back button. Override the back button in Activities that need it and run your code

        @Overrride
        public void onBackPressed(View v) {
         // save data first
    
          Intent MainActivityIntent = new Intent(CurrentActivityName.this, MainActivityClass); 
          startActivity(MainActivityIntent);
          super.onBackPressed();
    }
    

    You can also use flags such as FLAG_ACTIVITY_CLEAR_TOP if you want to remove all Activities between the current one and the target Activity(here MainActivity) by calling setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)