没有调用片段的onActivityResult

时间:2014-07-27 15:56:19

标签: java android android-activity android-fragments lifecycle

我有两个Fragment' s:HomeworkListFragment和HomeworkFragment。 HomeworkFragment将启动一个HomeworkFragment实例,如下所示:

HomeworkObject homework = new HomeworkObject();
HomeworkLab.get(getActivity()).addHomework(homework);
Intent i = new Intent(getActivity(),HomeworkPagerActivity.class);
i.putExtra(HomeworkFragment.EXTRA_HOMEWORK_ID, homework.getId());
startActivityForResult(i,REQUEST_DELETE_HOMEWORK_ID);

在我的HomeworkFragment类中,我希望用户能够按下选项菜单中的按钮,删除由HomeworkListFragment传递给HomeworkFragment的HomeworkObject实例。

因此,我需要的是能够让HomeworkFragment将包含HomeworkObject的id的结果返回到HomeworkListFragment,以便它可以处理删除:

@Override
public boolean onOptionsItemSelected(MenuItem item){
    switch(item.getItemId()){
        case android.R.id.home:
            if(NavUtils.getParentActivityName(getActivity()) != null){
                NavUtils.navigateUpFromSameTask(getActivity());
            }
            return true;
        case R.id.menu_item_detail_delete_homework: //Deleting the Homework
            Intent i = new Intent();
            i.putExtra(EXTRA_DELETE_HOMEWORK_ID, mHomework.getId());
            getActivity().setResult(Activity.RESULT_OK, i);
            //getActivity().finish();
            NavUtils.navigateUpFromSameTask(getActivity());
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

我尝试过以下操作,但HomeworkListFragment中的onActivityResult从未被调用过!

正如你所看到我试图调用getActivity()。finish()但我在其他帖子中读到这不是正确的方法..我也尝试过navigateUpFromSameTask ..这也错了吗?

这是我的HomeworkListFragment onActivityResult:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(int requestCode, int resultCode, Intent data);
    Toast.makeText(getActivity(), "HERE", Toast.LENGTH_SHORT).show();    
    if  (requestCode == REQUEST_DELETE_HOMEWORK_ID){
        String filename = data.getStringExtra(HomeworkFragment.EXTRA_DELETE_HOMEWORK_ID);
        Toast.makeText(getActivity(), "ID: "+filename, Toast.LENGTH_SHORT).show();    
    }
}

更新:

我不应该打电话:NavUtils.navigateUpFromSameTask(getActivity()); ?

1 个答案:

答案 0 :(得分:0)

奇怪的是,我错过了super.onActivityResult(requestCode,resultCode,data);

之前我曾引用错误的行,但无法找出原因。现在我拥有它!但它花了我两个月......