MapActivity in TabHost Fragment disappearing after tab switch

前端 未结 2 1434
忘掉有多难
忘掉有多难 2021-02-10 03:24

I\'m trying to display a map in a set of tabs, using fragments. The problem I\'m having is the map activity disappears if the user navigates to another fragment, then back. How

相关标签:
2条回答
  • 2021-02-10 03:29

    I worked around this issue as follows...

    I had a class level variable:

    private View mMapViewContainer;
    

    I created the tab containing the map as follows (where MyMapActivity is the MapActivity displayed in the tab and mTabHost is the TabHost) in the onViewCreated method of my Fragment:

    // Map tab
    Intent intent = new Intent(getActivity(), MyMapActivity.class);
    Window window = mLocalActivityManager.startActivity(MAP_ACTIVITY_TAG, intent);
    mMapViewContainer = window.getDecorView();
    mMapViewContainer.setVisibility(View.VISIBLE);
    mMapViewContainer.setFocusableInTouchMode(true);
    ((ViewGroup) mMapViewContainer).setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
    
    View tab = getActivity().getLayoutInflater().inflate(R.layout.tab_background, null);
    ((TextView) tab.findViewById(R.id.tv_tab_title)).setText(getResources().getString(R.string.map));
    TabSpec tabSpec = mTabHost.newTabSpec(MAP_TAB_TAG).setIndicator(tab).setContent(new TabContentFactory() {
    
        @Override
        public View createTabContent(String tag) {
            return mMapViewContainer;
        }
    });
    mTabHost.addTab(tabSpec);
    

    And then in the fragments onStop() method I did the following:

    @Override
    public void onStop() {
        super.onStop();
    
        ((ViewGroup) mMapViewContainer.getParent()).removeView(mMapViewContainer);
    }
    

    Now the map is re-displayed when the user navigates to another fragment and then back.

    0 讨论(0)
  • 2021-02-10 03:33

    If you used ViewPager in your project, call setOffscreenPageLimit() for it like shown below :

    this.mViewPager.setOffscreenPageLimit(fragments.size());

    where fragments is the Vector of fragments you've created

    0 讨论(0)
提交回复
热议问题