簡體   English   中英

保存以編程方式為片段創建的視圖並在onresume中恢復

[英]save view created programmatically for a fragment and restore in onresume

在我的應用程序中,我有一個帶有選項卡的活動,用於管理6個片段。 我有一些片段,我必須根據從webservice下載的一些數據以編程方式創建一些視圖。 如何保存以編程方式創建的視圖,並在片段恢復時將其還原,而無需每次都重新創建它們?

您應該對片段使用單例模式

Java中的單例是只能為其創建一個實例的類,提供了對該實例的全局訪問點。 單例模式描述了如何對其進行歸檔。

例如:

    public class YourFragment extends Fragment {
      private static YourFragment uniqInstance;

      private YourFragment () {
      }

      public static YourFragment getInstance() {
        if (uniqInstance == null) {
          uniqInstance = new YourFragment();
        }
        return uniqInstance;
      }
      .........
} 

如果要訪問您的片段,請致電:

YourFragment.getInstance();

如果要訪問片段中的方法,應調用:

YourFragment.getInstance().yourMethod();

當然,您訪問的方法必須聲明為public。

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM