2

当我在Activity B中的回调完成时,我如何在Activity A中显示小吃栏(coordinatorLayout 在这里)?Snackbar 需要我的 coordinatorLayout 但我不能从 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
        }
    });
}

感谢帮助。

4

1 回答 1

5

您应该从 Activity A 打开 Activity B 就像

startActivityForResult(activityBIntent, FORM_REQUEST_CODE);

然后当您提交表单时,以结果完成活动 B

@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();
}

并在活动 A 中对此做出反应

@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();
            }
    }
}

另一种解决方案是在 IntentService 中调用服务器,并在调用完成后立即使用某种事件总线(即Otto)向 Activity A 发送事​​件。

于 2016-02-16T18:58:40.140 回答