0

I have an app in which I swap two fragments. The fragments are in a LinearLayout. Below the linearlayout I have icons (ImageViews) that when clicked hides or shows the appropriate fragment. When the app first loads, everything is fine. After I exit my app and use another app then return to my app the fragments dont hide/show when I click the icons (ImageView). WHy is this happening? Does it have something to do with the activity life cycles?

xml_layout:

       <LinearLayout 
                android:id="@+id/Linearlayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                >


            </LinearLayout>









   onCreate()
    {
          ft = this.getSupportFragmentManager()
                    .beginTransaction();
          frag1= new Frag1();
          frag2= new  Frag2();
          ft.add(R.id.linearlayout,frag1);
          ft.add(R.id.linearlayout, frag2);
          ft.hide(frag1).show(frag2);
          ft.commit();



           icon1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {


                ftt =  MainActivity.this.getSupportFragmentManager()
                        .beginTransaction();
                ftt.hide(frag2).show(frag1);

                ftt.commit();
            }
        });


     }
sara roberts
  • 63
  • 1
  • 1
  • 11

2 Answers2

0

I think your problem is in this line:

ft.hide(frag2).show(frag2);

You want to hide frag1 and show frag2:

ft.hide(frag1).show(frag2);
iRuth
  • 2,737
  • 3
  • 27
  • 32
-1

Yes, the answer relates to the activity cycle. You need to override onCreateView and put your onClickListener inside of that. The onCreate is only getting called when the activity is first created. OnCreateView is called immediately after that, but it is also called when your activity is brought back to the front after you return from another activity.

  • the icons are not part of the Fragment, they are part of the Activity layout – sara roberts Feb 11 '15 at 23:37
  • Sara, I edited my comment to change 'fragment' to 'activity.' But my comment on the lifecycle stands. OnCreate is getting called only when the activity is first created, or if it gets destroyed, when it is recreated. When you move to another app, your activity is not necessarily destroyed by Android, it is put on the stack and only destroyed if necessary due to a lack of memory. Your onClickListener needs to be in another method that will be called when your activity is made visible again. – michael kagan Feb 12 '15 at 00:09