Switching between Fragments with button

Kapparino

In my app, I have one activity and two fragments. What I'm trying to do, is to navigate between this two fragments back or front with button. Each navigate button is defined in fragment.

The first problem is, with the code that is below, I get the exception on application run:

E/AndroidRuntime: FATAL EXCEPTION: main
        java.lang.RuntimeException: Unable to start activity ComponentInfo{...MainActivity}: 
            java.lang.IllegalArgumentException: No view found for id 0x7f0c0050 for fragment Fragment1{b41da690 #0 id=0x7f0c0050}
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
        at android.app.ActivityThread.access$600(ActivityThread.java:130)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4745)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        at dalvik.system.NativeStart.main(Native Method)
        Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0c0050 for fragment Fragment1{b41da690 #0 id=0x7f0c0050}
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:823)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035)
        at android.app.BackStackRecord.run(BackStackRecord.java:635)
        at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397)
        at android.app.Activity.performStart(Activity.java:5017)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2032)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
        at android.app.ActivityThread.access$600(ActivityThread.java:130) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
        at android.os.Handler.dispatchMessage(Handler.java:99) 
        at android.os.Looper.loop(Looper.java:137) 
        at android.app.ActivityThread.main(ActivityThread.java:4745) 
        at java.lang.reflect.Method.invokeNative(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:511) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
        at dalvik.system.NativeStart.main(Native Method) 

CODE:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // set desired fragment for the first time
        setFragment(this, new Fragment1());
    }

    public void switch_fragment(View view, String fragmentID) {
        Fragment newFragment = null;
        switch (fragmentID) {
            case Fragment1.ID:
                newFragment = new Fragment1();
                break;
            case Fragment2.ID:
                newFragment = new Fragment2();
                break;
        }
        setFragment(this, newFragment);
    }

    public static void setFragment(Activity activity, Fragment fragment) {
        FragmentTransaction fragmentTransaction = activity.getFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_placeHolder, fragment);
        fragmentTransaction.commit();
    }
}

main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@+id/fragment_placeHolder"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>

    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/fragment1"
        />
    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/fragment2"
        />
</RelativeLayout>

Fragment1.java

public class Fragment1 extends Fragment {

    public static final String ID = "1";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment1, container, false);
    }

}

fragment1.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="GO TO FRAGMENT 1"
        android:id="@+id/btn_1"
        android:onClick="switch_fragment"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        />
</RelativeLayout>

Fragment2.java

public class Fragment2 extends Fragment {

    public static final String ID = "2";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment2, container, false);
    }

}

fragment2.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="GO TO FRAGMENT 2"
        android:id="@+id/btn_2"
        android:onClick="switch_fragment"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        />
</RelativeLayout>

If this sample is wrong way of achieving this, can you please link some similar example for newbie.

T D Nguyen

You missed a very important part is setContentView and before using replace you should have an existing fragment. So in onCreate change:

// set desired fragment for the first time
        setFragment(this, new Fragment1());

Should be changed to:

   setContentView(R.layout.main_activity);//then
   // set desired fragment for the first time
   FragmentManager fm = getSupportFragmentManager();
   FragmentTransaction ft = fm.beginTransaction();

    // The id specified here identifies which ViewGroup to
    // append the Fragment to.
    ft.add(R.id.fragment_placeHolder, new Fragment1());
    ft.commit();

Try to replace:

... activity.getFragmentManager()

With:

... getSupportFragmentManager()

and remove:

<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/fragment1"
    />
<fragment
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/fragment2"
    />

Finally, change the switch_fragment to:

public void switch_fragment(View view) {
        Fragment newFragment = null;
        switch (view.getID()) {
            case R.id.btn_2:
                newFragment = new Fragment1();
                break;
            case R.id.btn_1:
                newFragment = new Fragment2();
                break;
        }
        setFragment(this, newFragment);
    }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Switching between fragments with back button

From Dev

Will Activity onpause be called when switching between fragments

From Dev

Android: Switching between different fragments using tabs

From Dev

NullPointerException when switching between fragments containing RecyclerView

From Dev

RecyclerView items disappear after switching between fragments

From Dev

Switching between fragments does not call onStop method

From Dev

How to handle camera while switching between fragments?

From Dev

Why is my button text not showing when switching fragments?

From Dev

My Navigation bar is not switching between fragments in Android Studio Kotlin

From Dev

wxPython: Switching between multiple panels with a button

From Dev

switching between visible and hidden using a button

From Dev

Xcode (iOS) - Switching Between Storyboards With The Press Of A Button

From Dev

wxPython: Switching between multiple panels with a button

From Dev

Switching fragments in navigation drawer

From Dev

No error in logcat but fragments are not switching

From Dev

Switching fragments in navigation drawer

From Dev

Fragments switching and lifecycle

From Dev

Transition between fragments via back button and home button

From Dev

Animate transaction between fragments when back button clicked

From Java

Switching between Android Navigation Drawer image and Up caret when using fragments

From Dev

How to make the toolbar appear when switching between fragments using CoordinatorLayout, Toolbar and fragment

From Dev

Using viewer page to switch between two fragments - however it disappears after switching into a fragment

From Dev

Jumping scrolling when switching fragments

From Dev

ClassCastException when switching Fragments into container

From Dev

Can I use one definition of two Button by switching between them?

From Dev

back button in toolbar of fragments

From Dev

back button navigation with fragments

From Dev

Switching Fragments in navigation drawer using onNavigationItemSelected()

From Dev

HOW TO Revert Action Bar after Switching Fragments

Related Related

  1. 1

    Switching between fragments with back button

  2. 2

    Will Activity onpause be called when switching between fragments

  3. 3

    Android: Switching between different fragments using tabs

  4. 4

    NullPointerException when switching between fragments containing RecyclerView

  5. 5

    RecyclerView items disappear after switching between fragments

  6. 6

    Switching between fragments does not call onStop method

  7. 7

    How to handle camera while switching between fragments?

  8. 8

    Why is my button text not showing when switching fragments?

  9. 9

    My Navigation bar is not switching between fragments in Android Studio Kotlin

  10. 10

    wxPython: Switching between multiple panels with a button

  11. 11

    switching between visible and hidden using a button

  12. 12

    Xcode (iOS) - Switching Between Storyboards With The Press Of A Button

  13. 13

    wxPython: Switching between multiple panels with a button

  14. 14

    Switching fragments in navigation drawer

  15. 15

    No error in logcat but fragments are not switching

  16. 16

    Switching fragments in navigation drawer

  17. 17

    Fragments switching and lifecycle

  18. 18

    Transition between fragments via back button and home button

  19. 19

    Animate transaction between fragments when back button clicked

  20. 20

    Switching between Android Navigation Drawer image and Up caret when using fragments

  21. 21

    How to make the toolbar appear when switching between fragments using CoordinatorLayout, Toolbar and fragment

  22. 22

    Using viewer page to switch between two fragments - however it disappears after switching into a fragment

  23. 23

    Jumping scrolling when switching fragments

  24. 24

    ClassCastException when switching Fragments into container

  25. 25

    Can I use one definition of two Button by switching between them?

  26. 26

    back button in toolbar of fragments

  27. 27

    back button navigation with fragments

  28. 28

    Switching Fragments in navigation drawer using onNavigationItemSelected()

  29. 29

    HOW TO Revert Action Bar after Switching Fragments

HotTag

Archive