2017-10-07 135 views
0

我有一個增強的循環,它會動態膨脹,但是與我的數組中保存的值數量相關的許多佈局。如何保存動態viewpager中保存的視圖狀態

這很好,但是,每次迭代都會調用一個方法,這種方法也有效,但是有一個很大的錯誤,我需要幫助解決。

想象一下,在我的數組中有5個項目,因此5個佈局是充氣的,在這些佈局中佈局上有一個小刮板類型部分。

現在,如果用戶在第1頁上,使用刮刮卡,然後移動到第2頁,使用刮刮卡等等,它工作正常。

但是,如果用戶在頁面1上,然後轉到第5頁然後回到第1頁(基本上是以隨機順序),則刮刮卡不起作用。

從我的理解,其原因是該方法被稱爲一個實現在每次迭代和視圖正在失去其狀態,如果用戶滾動回滾或隨機順序滾動。

因此,我需要一種方法來保存viewpager中創建的視圖狀態。

這是可能的我的情況?我盡力找到解決方案,但找不到與我的問題相關的內容。

以下是有問題的代碼片段。感謝您的任何指導或建議!

for (String x : array1) { 
       //loop out the number of layouts relative to the number of questions held in x 
       View current_layout = LayoutInflater.from(getActivity()).inflate(R.layout.question_fragment, null); 
       //use the pageAdapter to add the layout to the users view 
       pagerAdapter.addView(current_layout); 

       //call method to add functionality to the scratchcard 
       isCorrect(current_layout); 
} 



public void isCorrect(View current_layout) { 



     ScratchoffController controller1 = new ScratchoffController(getActivity()) 
       .setThresholdPercent(0.40d) 
       .setTouchRadiusDip(getActivity(), 30) 
       .setFadeOnClear(true) 
       .setClearOnThresholdReached(true) 
       .setCompletionCallback(() -> { 
       }) 
       .attach(current_layout.findViewById(R.id.scratch_view1), current_layout.findViewById(R.id.scratch_view_behind1)); 



     ScratchoffController controller2 = new ScratchoffController(getActivity()) 
       .setThresholdPercent(0.40d) 
       .setTouchRadiusDip(getActivity(), 30) 
       .setFadeOnClear(true) 
       .setClearOnThresholdReached(true) 
       .setCompletionCallback(() -> { 
       }) 
       .attach(current_layout.findViewById(R.id.scratch_view2), current_layout.findViewById(R.id.scratch_view_behind2)); 

     ScratchoffController controller3 = new ScratchoffController(getActivity()) 
       .setThresholdPercent(0.40d) 
       .setTouchRadiusDip(getActivity(), 30) 
       .setFadeOnClear(true) 
       .setClearOnThresholdReached(true) 
       .setCompletionCallback(() -> { 
       }) 
       .attach(current_layout.findViewById(R.id.scratch_view3), current_layout.findViewById(R.id.scratch_view_behind3)); 

     ScratchoffController controller4 = new ScratchoffController(getActivity()) 
       .setThresholdPercent(0.40d) 
       .setTouchRadiusDip(getActivity(), 30) 
       .setFadeOnClear(true) 
       .setClearOnThresholdReached(true) 
       .setCompletionCallback(() -> { 
       }) 
       .attach(current_layout.findViewById(R.id.scratch_view4), current_layout.findViewById(R.id.scratch_view_behind4)); 



    } 
+0

您應該將代碼發佈到實際的視圖傳呼機實現中(比如它持有碎片或視圖?)。您的代碼示例缺乏上下文。 – dominicoder

回答

0

我ussually使用ViewPager與片段和你提到已經happend給我時,我儘量保持該片段實例的引用(對我來說)的viewpager之外的東西。

發生這種情況是因爲viewpager可能會在您按照提及的方式重新選中選項卡時創建它包含的Fragment的新實例。發生這種情況時,您在viewpager外部持有的實例引用不再是viewpager顯示的內容。

在你的情況,according to this question,你必須過於instatiateItemdestroyItem。我認爲你可以使用這些方法來保存狀態恢復狀態,並且你可以在調用instantiateItem時更新任何外部引用。