Search code examples
androidandroid-layoutandroid-studioandroid-fragmentssearchview

Action bar back button returning to previous activity on expanded SearchView


I've got a SearchView which expands to search automatically when starting an activity, but I want the back button to the left of it to return to the previous activity instead of closing it. Any ideas on how to achieve this?

Thanks.


Solution

  • Try This

    public void onBackPressed() {
        showExitAlertBox();
    }
    
    public void showExitAlertBox() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setMessage("You want to quit the play?");
    
        //Yes Quit then go to category page
        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int button) {
                Intent intent = new Intent(getApplicationContext(), PREVIOUSACTIVITY.class);
                startActivity(intent);
                finish();
            }
    
        });
    
        //no Quit stay on same page
        alertDialog.setNegativeButton("NO", null);
        alertDialog.show();
    
    }