Search code examples
androidandroid-fragmentsandroid-viewpagerandroid-canvasswipe

ViewPager, lines drawn with canvas.drawPath disappear when switching the fragment


I made a ViewPager layout and 3 layouts for the fragments, every fragment got also an Activity, first_fragment.java, second, third. The first fragment contains a draw area, in which you can draw lines. The second contains buttons, for choosing color and stroke width. The third contains a statistic for used colors and widths.

The Problem is now, if I swipe from the first to the second and back the drawn lines are still there, but if I switch from, first to second to third, and then back, the drawn lines disappear. The second and third fragments are completly equal at the moment, So why do the lines disappear one time and the other not?

I used a setOffscreenPageLimit and set the limit to 2. In general the limit gives you the count of pages you can swipe to the left and right without recreating the fragments! So in my case 2 to the left and 2 to the right!

 ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
 pager.setOffscreenPageLimit(2);

Solution

  • Lines dissapear because Android system unloads fragments from memory in ViewPager.

    You have 2 solutions:

    1. ask ViewPager doesn't destroy a fragment:

      ViewPager pager = (ViewPager) findViewById(R.id.viewPager); pager.setOffscreenPageLimit(2);

    2. use onSaveInstanceState() callback for saving fragment state and recreate fragment in onCreate(Bundle state)

      public class MyFragment extends Fragment { private static final String EXTRA_PARAM = "my_custom_param1"; private static final String EXTRA_PARAM2 = "my_custom_param2";

      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
              Bundle savedInstanceState) {
      
          if (savedInstanceState != null) 
          {
               //restore state
               Log.d("restore_state", savedInstanceState.getString(EXTRA_PARAM));
          }
      
          return content;
      
      }
      
      @Override
      public void onSaveInstanceState(Bundle state) {
          super.onSaveInstanceState(state);
      
          state.putString(EXTRA_PARAM, "whatever you want");
          state.putInt(EXTRA_PARAM2, 12345);
        }
      

      }

    The 2nd solution is preferable