简体   繁体   中英

Android, check if back Button was pressed

i have two views and activities. On the first there is a spinner. On the second, you can create new entries (Stored in database for the spinner in activity 1). If the user is finished and pressed the back button, i have to refresh the spinner on activity 1 (because of the new entries).

Ist there a possibility to check, if the app returns to activity 1, because the back button in activity 2 was pressed?

I know, i can do it with the onResume Method, but this method is called EVERYTIME i return to activity one and not ONLY because of the back button.

I want to refresh the spinner only when the back button was pressed.

Any solution? Can i Check if the back button was pressed in the onResume method?

You can override onBackPressed() in the Second Activity. This will get called when the user presses the back button.

You can pass the information as a boolean hasBackPressed = true in the setResult()

Starting Activity 2 from Activity 1:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

Passing info back from Activity 2:

    @Override
    public void onBackPressed() {
        Intent returnIntent = new Intent();
        returnIntent.putExtra("hasBackPressed",true);
        setResult(Activity.RESULT_OK,returnIntent);
        finish();
    }

Receiving data in Activity 1:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            boolean hasBackPressed = data.getBooleanExtra("hasBackPressed");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}

You can start Activity 2 for result, using startActivityForResult() . On Activity 2 you can set the result to RESULT_OK when new items have been added. Then, in the onActivityResult() method of Activity 1 you can check the returned result and update your data, if needed.

Override the onBackPressed() method and take the action inside this function.

@Override
public void onBackPressed() {
    // your stuff here

    super.onBackPressed();
}

Use startActivityForResult() to start the second activity, and return some value in the onBackPressed() of the second activity. Catch that in onActivityResult() , and refresh the spinner there.

Look into this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM