MapActivity in TabHost Fragment disappearing after tab switch

前端 未结 2 1433
忘掉有多难
忘掉有多难 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.

提交回复
热议问题