Android - Snackbar between Activities

2019-05-23 06:34发布

问题:

How i can show snackbar in Activity A (coordinatorLayout is here) when my callback in Activity B is done ? Snackbar need my coordinatorLayout but i can't give it from Activity B..

Activity B :

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if(id == android.R.id.home) {
        this.finish();
        return true;
    } else if(id == R.id.action_add) {
        callAddObject();
        this.finish();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

public void callAddObject() {
    [...]
    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            Log.d(TAG, "onFailure: " + e.getMessage());
            // show snackbar in Activity A
        }

        @Override
        public void onResponse(Response response) throws IOException {
            Log.d(TAG, "onResponse: " + response.body().string());
            // show snackbar in Activity A
        }
    });
}

Thanks for help.

回答1:

You should open Activity B from Activity A like

startActivityForResult(activityBIntent, FORM_REQUEST_CODE);

then when your form is submitted, finish Activity B with a result

@Override
public void onFailure(Request request, IOException e) {
    Log.d(TAG, "onFailure: " + e.getMessage());
    // You might not want to finish the activity here, instead, you can show an error here
}

@Override
public void onResponse(Response response) throws IOException {
    Log.d(TAG, "onResponse: " + response.body().string());
    setResult(FORM_SUBMITTED);
    finish();
}

and react to that back in Activity A like

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    switch (requestCode) {
        case FORM_REQUEST_CODE:
            if (resultCode == ActivityB.FORM_SUBMITTED) {
                Snackbar.make(mView, "Form submitted", Snackbar.LENGTH_SHORT).show();
            }
    }
}

Alternative solution would be to make the call to server in, say, an IntentService and use some kind of event bus (i.e. Otto) to send an event to Activity A as soon as the call finishes.