更新资料
活动A ==>托管MyFragment,从这里开始,用户启动==> ActivityB从这里我需要从此活动中获取一些值,例如,值整数和在ActivityA中托管的MyFragment的一些字符串

我有MyFragment这样启动activityB:

 Intent intent = new Intent(getActivity(),NewsCommentActivity.class);
        intent.putExtra("MNewsFeed", new Gson().toJson(newsFeed));
        intent.putExtra("idCommentBadge",idCommentBadge);
        startActivityForResult(intent,addComment);


然后,当用户启动活动并完成活动时,我试图像这样从ActivityB传递一些值到MyFragment:

@Override
    public void onBackPressed() {
        super.onBackPressed();
        //set ok result before finish the activity

        Intent returnIntent = new Intent();
        returnIntent.putExtra("idBadgeComment", idBadgeComment);
        returnIntent.putExtra("totalCommentInserted", totalCommentInserted);
        setResult(RESULT_OK, returnIntent);
        finish();
    }


并且我在MyFragment中实现了onActivityResult:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "Result from News Comment ");

        if(resultCode== Activity.RESULT_OK){
            Log.i(TAG, "Result from News OK");
            if(requestCode==addComment){
                Log.i(TAG, "Result ReqCode Oke");

                int idBadgeComment = data.getExtras().getInt("idBadgeComment");
                int totalCommentInserted = data.getExtras().getInt("totalCommentInserted");

                Log.i(TAG, "idComment: "+idBadgeComment);
                Log.i(TAG, "Total Comment Inserted: "+totalCommentInserted);
            }
        }
    }


我也曾在托管MyFragment的ActivityA中调用onActivityResult:

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

        /**
         * call below code to get the result on the fragment
         */
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.viewpager);
        fragment.onActivityResult(requestCode, resultCode, data);

    }


当我尝试上面的代码时,我只会得到Log.i(TAG, "Result from News Comment ");,而没有得到RESULT_OK值,并且Intent数据为null,有人可以指出我在哪里出错了吗?以及如何将值从活动传递到片段?还是比使用onActivityResult更好的方法?

最佳答案

您可以尝试将super.onBackPressed();作为最后一行,因为RESULT_CANCELED会在返回时返回。

09-11 19:18