OnActivityResult不是在fragement中调用的

时间:2016-08-01 14:16:12

标签: android android-fragments

我的Main活动有两个标签(片段)。在片段中,我通过startactivityforresult调用一个新活动。在新活动中,我按下后退按钮时输出结果代码。问题是片段中的“OnActivityResult”从未被调用过,我无法理解为什么!。

片段代码:

RequestListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            view.setSelected(true);
            Intent SelectedRentRequest = new Intent(getActivity(), SelectedRentRequest.class);
            SelectedRentRequest.putExtra("CarNumbers", SCarNumbers);
            startActivityForResult(SelectedRentRequest, 1);
        }
    });

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1 && resultCode == 1 && data != null) {
        LoadList();
        Toast.makeText(getContext(), "hi", Toast.LENGTH_LONG).show();
    }
}

第二个活动代码(后退部分):

@Override
public void onBackPressed() {
    Intent intent = new Intent();
    setResult(1, intent);
    finish();
}

主要活动(标签部分):

TabLayout tabLayout = (TabLayout) findViewById(R.id.Maintab);
    assert tabLayout != null;
    tabLayout.addTab(tabLayout.newTab().setText("سيارات محافظتك"));
    tabLayout.addTab(tabLayout.newTab().setText("طلبات السيارات"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    final PagerAdapter adapter = new PagerAdapter
            (getSupportFragmentManager(), tabLayout.getTabCount(), bundle);
    assert viewPager != null;
    viewPager.setAdapter(adapter);

    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

3 个答案:

答案 0 :(得分:1)

为了使onActivityResult在你的片段中起作用,你必须在你的活动中实现它,因为setResult方法将结果返回给托管片段而不是直接托管片段的Activity

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

答案 1 :(得分:1)

确保您使用的是最新的支持库:

compile 'com.android.support:support-v7:24.1.1'

相关错误已在23.2中修复。

还要确保父活动在清单中指定了有效的launchMode。例如。如果singleTask

,则startActivityForResult

会立即调用该方法

答案 2 :(得分:0)

尝试在Activity中添加onActivityResult,这个将在调用super时调用并调度到片段:

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