在我们销毁活动时如何清除片段使用的资源? [英] How to clear the resources used by the fragment while we destroy the activity?

查看:90
本文介绍了在我们销毁活动时如何清除片段使用的资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

For example, I have added the TextView inside the fragment as below.

        var adaptor = new GenericFragmentPagerAdaptor(SupportFragmentManager); // where GenericFragementPagerAdaptor is a sub-class derived from FragementPagerAdaptor

        adaptor.AddFragmentView((i, v, b) => {
            var view = i.Inflate(Resource.Layout.tab, v, false);
            textView = new TextView(view.Context);
            textView.Text = "Test1";
            view.FindViewById<FrameLayout>(Resource.Id.mainFrame).AddView(textView);
            return view;

If I am destroying the current activity means, all the resources related to the fragment should be cleared.Where and how can I do that? Please, anyone suggests me.





我拥有什么尝试过:



我已尝试通过以下方式给出OnDestroyView()和OnDetach()覆盖Fragment类中的方法



this.FragmentManager.Fragments.Clear();



但它没有用。



What I have tried:

I have tried by given like below in OnDestroyView() and OnDetach() override methods in Fragment class

this.FragmentManager.Fragments.Clear();

But it did not worked.

推荐答案

如果我理解你的要求我认为你想要做的是使用IDisposable接口,它将为你处理资源的清理。



您使用IDisposable的用法将是





If i understand what you are asking i think what you want to do is use the IDisposable interface which will handle the cleanup of resources for you.

Your usage having used IDisposable would then be


using(var adaptor = new GenericFragmentPagerAdaptor(SupportFragmentManager))
{

        adaptor.AddFragmentView((i, v, b) => {
            var view = i.Inflate(Resource.Layout.tab, v, false);
            textView = new TextView(view.Context);
            textView.Text = "Test1";
            view.FindViewById<FrameLayout>(Resource.Id.mainFrame).AddView(textView);
            return view;
		});
}





通过这种方式, using(){} 之外的任何内容都会垃圾处理流程会自动清理。



实施IDisposable的例子如下:





By doing it this way, anything outside the using(){} would be automatically cleaned up by the garbage disposal process.

An example of implementing IDisposable would be something like this:

public class MyClass : IDisposable
{
   private bool Disposed { get; set; }

   public void Dispose()
   {
      this.Dispose(true);
      GC.SuppressFinalize(this);
   }
   
   protected virtual void Dispose(bool disposing)
   {
      if (!this.Disposed)
      {
         if (disposing)
         {
            // do your code cleanup here to free resources and what not
         }
      }

      this.Disposed = true;
   }
}


//usage

using(var cl = new MyClass())
{
   //Run some code using the class here
}

// Disposable method has been run at this point


这篇关于在我们销毁活动时如何清除片段使用的资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆