android-当片段事务与FrameLayout一起使用时,为什么片段调用OnCreate / OnCreateView?
作者:互联网
我的应用程序的主页上有一个FrameLayout.
我在活动开始时实例化了两个片段,并且试图使用菜单按钮在片段之间进行交换.
scanHistoryFrag = new HistoryFragment();
scanFrag = new ScanFragment();
我从不替换这些对象-我在应用程序的整个生命周期中都使用相同的对象.但是,当我在FrameLayout中交换它们时…
private void ChangeFragment(Android.Support.V4.App.Fragment fragment)
{
Android.Support.V4.App.FragmentTransaction ft = SupportFragmentManager.BeginTransaction();
ft.Replace(Resource.Id.fragmentContainer, fragment);
ft.Commit();
}
再次在Fragment上调用OnCreate和OnCreateView …这意味着我在该片段上创建后所做的任何调整都将再次被初始值覆盖.我似乎找不到任何解释为什么发生这种情况或如何避免这种情况.
因为我正在使用菜单按钮来切换它们,所以OnOptionsItemSelected会调用ChangeFragment方法.
解决方法:
I never replace these objects – I use the same ones throughout the lifecycle of the application.
Fragment子类的初始化只是创建该类对象的实例,该类的构造函数将被调用,但是除非添加了此Fragment,否则它不会经历Fragment的生命周期,有关更多信息,请参见Fragments.为了更容易理解,我个人认为实例保存了此Fragment类的数据状态,但是生命周期事件处理此Fragment的视图状态.
which means any adjustments I made post creation on that fragment are overwritten with initial values again.
你是对的.为了避免再次覆盖初始值,我们可以将片段的视图缓存在OnCreateView中,例如:
private View rootView;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
// return inflater.Inflate(Resource.Layout.YourFragment, container, false);
if (rootView == null)
{
//first time creating this fragment view
rootView = inflater.Inflate(Resource.Layout.fragmentlayout1, container, false);
//Initialization
//TODO:
}
else
{
//not first time creating this fragment view
ViewGroup parent = (ViewGroup)rootView.Parent;
if (parent != null)
{
parent.RemoveView(rootView);
}
}
return rootView;
}
标签:android-fragments,xamarin-android,android 来源: https://codeday.me/bug/20191111/2022559.html