Android - 活动之间的小吃

时间:2015-07-10 14:45:01

标签: android android-activity android-snackbar snackbar

活动B 中的回调完成后,如何在活动A (coordinatorLayout在这里)中显示snackbar? Snackbar需要我的CoordinatorLayout但是我不能从Activity B中提供它..

活动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
        }
    });
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:5)

您应该从活动A中打开活动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();
}

然后在提交表单时,使用结果

完成活动B.
@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();
            }
    }
}

并在活动A中对此作出反应,如

Math.abs

替代解决方案是在IntentService中调用服务器并使用某种事件总线(即Otto)尽快向活动A发送事件电话结束时。