Android: How to simulate back button

为君一笑 提交于 2019-12-10 13:26:50

问题


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.


回答1:


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.




回答2:


If you are using Activities to show different screen then simply finish the activity with some result based on a button click and you can pass some Activity Result value back which can then be handled in onActivityResult of previous activity.

Adding some pseudo code. Assuming you have two Activty A and B and you go from A -> B and then from B -> A

in Activity A

 startActivityforResult(new Intent(A.this, B.class), 1234);

 onActivityResult(......) {
    if (1234 == requestCode) {
        switch (resultCode) {
             /* Do your processing here like clear up old values and so on */
        }
    }
 }

in Activity B

onClick() {

  if (v == backBtn) {
           Intent resultIntent = new Intent();
    setResult(Activity.RESULT_OK, resultIntent);
    finish();
 }
}



回答3:


As said earlier, just finish your activity:

myButton.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        finish();
    }
});



回答4:


All solutions on this post are too complex. The most simple is on this post:

Android - Simulate Back Button

It's the last solution on the post:

this.onBackPressed();

OR

getActivity().onBackPressed();

Dependely from where you are calling it.




回答5:


In your soft Back button onClick event write

Intent _intent = new Intent(PresentActivity.this,PreviousActivity.class);
startActivity(_intent);


来源:https://stackoverflow.com/questions/6897785/android-how-to-simulate-back-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!