在片段的Andr​​oid浏览重用片段、Andr、oid

2023-09-04 10:28:43 作者:森里失了鹿

我想救我的视图状态在我的片段,但我担心我做渗出我的活动。下面是我在做什么:

  @覆盖
公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,捆绑状态){
   如果(MVIEW!= NULL){
      查看oldParent = mView.getParent();
      如果(oldParent!=容器){
         ((ViewGroup中)oldParent).removeView(MVIEW);
      }
      返回MView的;
   }
   其他{
      MVIEW = inflater.inflate(R.id.fragview,空)
      返回MView的;
   }
}
 

我很担心,因为我知道所有浏览守住一个方面,我不知道这是否是活动上下文或应用程序上下文,如果从充气膨胀。或许,这将是一个更好的主意,以务实的态度创建视图,并使用getActivity()设置其属性。getApplication(),而不是使用充气。我想AP preciate有这方面的反馈。

谢谢!

编辑:确认活动泄漏,虽然这code的伟大工程没有做到这一点:*(

解决方案   

我想救我的视图状态在我的片段,但我担心我做渗出我的活动。

使用的onSaveInstanceState()(在片段)和 onRetainConfigurationInstance()(在活动),维持视图状态跨越配置更改。我不是很肯定视图状态还有什么其他你可能会提及。

  

我很担心,因为我知道所有浏览守住一个方面,我不知道这是否是活动上下文或应用程序上下文,如果从充气膨胀。

自从使用了应用程序的观点通胀似乎并没有很好地工作,你应该从活动充气 。 ,因此,该意见将举行一个引用夸大他们的活动。

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.