简体   繁体   中英

Get a Fragment to override onCreateView when screen turns on

My problems is that onCreateView is not called in my MapFragment to reinstantiate/create the Fragment view (a MapView container) that is removed under onPause and onStop, and thus is null. Therefore the Fragment content displays black since map view is null.

This happens only under one condition, and that is when I power the screen off and on again. onCreateView acts normal when I swipe back to the mapview Fragment after it having been paused. The screen needs to go off often since I'm working on a location-based game.

Any help here would be greatly appreciated! =)

I have a FragmentActivity that has three tabs, ViewPager, FragmentPagerAdapter, and all that:

mapFragment = Fragment.instantiate(this, MapFragment.class.getName());
fragments.add(mapFragment);
fragments.add(Fragment.instantiate(this, NavHelperActivity.class.getName()));
fragments.add(Fragment.instantiate(this, CompassTabActivity.class.getName()));
mPagerAdapter  = new MyPagerAdapter(super.getSupportFragmentManager(), fragments);

pager = (ViewPager)super.findViewById(R.id.viewpager);
pager.setAdapter(this.mPagerAdapter);

MapFragment onCreateView(..) does this:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// This is where you specify you activity class
Intent i = new Intent(getActivity(), MapTabActivity.class);
Window w = mLocalActivityManager.startActivity("tag", i);
mapViewContainer = w.getDecorView();
mapViewContainer.setVisibility(View.VISIBLE);
mapViewContainer.setFocusableInTouchMode(true);
((ViewGroup)
mapViewContainer).setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
return mapViewContainer; }

And the onPause has to remove the map view:

if (mapViewContainer != null) {
mapViewContainer.setVisibility(View.GONE);
((ViewGroup) mapViewContainer.getParent()).removeView(mapViewContainer);
mapViewContainer = null;
}

EDIT, UPDATE, SOLUTION:

First, don't null mapViewContainer explicitly.

Set class variable:

private static ViewGroup parent;

Override onStart with this code:

@Override
public void onStart() {
     super.onStart();
     parent = mapViewContainer.getParent();
}

In onResume, do:

@Override
public void onResume() {
    super.onResume();

    if (mapViewContainer != null) {
        ((ViewGroup) parent).removeView(mapViewContainer);
        ((ViewGroup) parent).addView(mapViewContainer);
    }
}

Rest of the code should remain the same.

Thanks to casaflowa for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM