質問

I am trying to save my View states in my fragment but I am concerned I make be leaking my Activity. Here is what I am doing:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state){
   if(mView != null){
      View oldParent = mView.getParent();
      if(oldParent != container){
         ((ViewGroup)oldParent).removeView(mView);
      }
      return mView;
   }
   else{
      mView = inflater.inflate(R.id.fragview, null)
      return mView;
   }
}

I am concerned because I know all Views hold onto a context and I don't know if it is the Activity context or Application context if inflated from the inflater. Perhaps it would be a better idea to pragmatically create the view and set its attributes using getActivity().getApplication() rather than use the inflater. I would appreciate any feedback on this.

Thanks!

EDIT: Confirmed Activity leak, although this code works great don't do it :*(

役に立ちましたか?

解決

I am trying to save my View states in my fragment but I am concerned I make be leaking my Activity.

Use onSaveInstanceState() (in the fragment) and onRetainConfigurationInstance() (in the activity) for maintaining "View states" across configuration changes. I am not quite certain what other "View states" you might be referring to.

I am concerned because I know all Views hold onto a context and I don't know if it is the Activity context or Application context if inflated from the inflater.

Since using the Application for view inflation does not seem to work well, you should be inflating from the Activity. And, hence, the views will hold a reference to the Activity that inflated them.

他のヒント

@schwiz é have implemented something similar.

I use the setRetainInstance in the fragment. on the fragment layout I have a FrameLayout placeholder where I put my webView inside.

This webView is created programmatically on the Fragment's onCreate using the Application Context, and I do a addView(webView) on the inflated layout in onCreateView().

webView = new WebView(getActivity().getApplicationContext());

And on onDestroyView I simply remove the webView from my framelayout placeholder.

It work really well, unless you try to play a video in fullscreen. That doesn't work because it expects an Activity Context

I am trying to save my View states in my fragment

In order to save and retain view's state you can just use View.onSaveInstanceState () and View.onRestoreInstanceState (Parcelable state)

It will help you to handle saving and restoring view state independantly from neither activity or fragment. See this answer for more information about it (how to prevent custom views from losing state across screen orientation changes)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top