Android: How to simulate back button

Jay Mayu picture Jay Mayu · Aug 1, 2011 · Viewed 14.7k times · Source

Currently my activity allows users to fill up certain data. Including spinner etc. When user click next system navigates to another screen. When I press back button on the phone previous activity loaded and filled data is available.

My requirement asks me to give a soft "Back" button in the UI. When user clicks it it navigats back to previous screen but the filled data is not available.

Is there any way to simulate the back button on a soft UI button onclick event??

Intent back = new Intent(ImagePreviewActivity.this, sendingpage.class);
startActivity(back);

Thanks in advance for your time.

Answer

Ovidiu Latcu picture Ovidiu Latcu · Aug 1, 2011

You'll just have to call your Activity finish() method when the user clicks the soft back button.

EDIT: just let your Activity implement OnClickListener and then in code

          myBackButton.setOnClickListener(this);
   ....

   public void onClick(View v) {
       if(v.getId()==R.id.YourBackButton){
           finish();
       }
   }

EDIT2: you can also call onBackPressed() from your Activity.