3

I have an Activity with few tabs managed by ViewPager. And there is one tab where i'd like to prevent closing activity when users click BACK button. Instead it loads upper level of data.

So my code in FragmentActivity looks like this

    @Override
public void onBackPressed() {
    boolean allowQuit = true;

    if (mTabsAdapter != null){
        if(mTabsAdapter.getItem(mTabsAdapter.selectedTab) instanceof backPressOverrider){
            allowQuit = ((backPressOverrider)mTabsAdapter.getItem(mTabsAdapter.selectedTab)).onCustomBackPressed();
        }
    }

    if (allowQuit) {
        super.onBackPressed();
    }
}

And it works - activity not finished and I see my fragment, but getActivity()in my fragment returns null. None of onDetach,onStop, onDestroy,.. was fired in fragment.

Is there any way to overcome this problem?

Andrew
  • 1,756
  • 3
  • 18
  • 31
  • what are you doing inside that method `.onCustomBackPressed()` are you calling any super methods? Have you checked if the fragment is still attached to the activity after that? – bogdan Jun 13 '13 at 08:23
  • 1
    Without seeing your adapter I'm assuming that `getItem()` simply creates a new fragment, one that is not attached to any `Activity`, and is not returning any of the fragment used by `ViewPager`'s adapter. – user Jun 13 '13 at 08:30
  • Luksprog, looks like you're right Here is getItem @Override public Fragment getItem(int position) { abInfo info = mTabs.get(position); return Fragment.instantiate(mContext, info.clss.getName(), info.args); } – Andrew Jun 13 '13 at 08:50
  • 1
    Then you need to retrieve the current fragment directly from the `ViewPager`. Have a look at the top answers from this question http://stackoverflow.com/questions/7379165/update-data-in-listfragment-as-part-of-viewpager – user Jun 13 '13 at 09:32
  • Yup! That's exactly what i did after your comment and it works perfect!Thank you @Luksprog ! – Andrew Jun 13 '13 at 13:52

0 Answers0