Aman
Aman

Reputation: 147

Changing fragments onClick of a button

I am trying to change the fragment when I click on a button. The button is inside a fragment and I want to go to another fragment. This code is not giving any error but not changing to desired fragment. It is just showing the background of container. Please help me why it is just showing the color of container and not changing to new fragment.

Here is my first Fragment-

public class IntroFragment1 extends Fragment {

    public IntroFragment1() {
        // Required empty public constructor
    }

    public static IntroFragment1 newInstance() {
        return new IntroFragment1();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_intro1, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        /**
         * Button to go to next tab in tutorial
         * */
        Button nextScreen = getView().findViewById(R.id.nextTabButtonIntro);
        nextScreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (vb1 != null) {
                    vb1.vibrate(300);
                }

                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                Fragment frag = IntroFragment2.newInstance();
                transaction.replace(R.id.containerIntroScreen, frag);
                transaction.commit();
            }
        });

    }//End of onViewCreated    
}

This is the XML of first Fragment. The next Button should take me to next fragment-

<LinearLayout 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:background="@color/colorPrimaryDark"
    android:orientation="vertical"
    android:weightSum="1"
    tools:context="com.example.fitbitsampleapp.AppIntroTabbedView.IntroFragment1">


        <TextView
            android:visibility="gone"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fontFamily="casual"
            android:text="Track your daily activities. Stay healthy, Stay smart."
            android:textSize="26dp" />

        <Button
            android:id="@+id/skipIntoButton"
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:layout_marginBottom="20dp"
            android:layout_marginRight="20dp"
            android:layout_weight="1"
            android:background="@drawable/background_button"
            android:fontFamily="casual"
            android:text="skip"
            android:textAllCaps="true"
            android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large"
            android:textColor="#000" />

        <Button
            android:id="@+id/nextTabButtonIntro"
            android:layout_width="0dp"
            android:layout_height="60dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentEnd="true"
            android:layout_marginBottom="20dp"
            android:layout_marginRight="20dp"
            android:layout_weight="1"
            android:background="@drawable/background_button"
            android:fontFamily="casual"
            android:text="next"
            android:textAllCaps="true"
            android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large"
            android:textColor="#000" />

    </LinearLayout>

This is the fragment, I want to go to-

public class IntroFragment2 extends Fragment {

    public IntroFragment2() {
        // Required empty public constructor
    }

    public static android.support.v4.app.Fragment newInstance() {
        IntroFragment2 fragment = new IntroFragment2();
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_intro2, container, false);
    }

The XML of the 2nd Fragment-

<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:background="@color/colorAccent"
 tools:context="com.example.fitbitsampleapp.AppIntroTabbedView.IntroFragment2">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:layout_gravity="center"
        android:text="2nd fragment" />

</RelativeLayout>

This is the layout of activity which has the fragments-

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.fitbitsampleapp.AppIntroTabbedView.IntroScreen">


    <android.support.v4.view.ViewPager
        android:background="#00F111"
        android:id="@+id/containerIntroScreen"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />


</android.support.design.widget.CoordinatorLayout>

So initially the app opens with 1st transaction as expected. However when I click on next button in fragment 1, it should take me to fragment 2. But it just shows the Background color of ViewPager after the Fragment Transaction.

EDIT: Here is my Main Activity as well which has the fragments-

public class IntroScreen extends AppCompatActivity {
    public static Vibrator vb1;
    public Button nextScreen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intro_screen);

        /***/
        vb1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

        /**
         *  Create the adapter that will return a fragment
         *  for each of the N primary sections of the activity.
         *  */
        SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        /** Set up the ViewPager with the sections adapter.*/
        ViewPager mViewPager = findViewById(R.id.containerIntroScreen);
        mViewPager.setAdapter(mSectionsPagerAdapter);

    }


    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        private SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }


        @Override
        public android.support.v4.app.Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            switch (position) {
                case 0:
                    return IntroFragment1.newInstance();

                case 1:
                    return IntroFragment2.newInstance();

                default:
                    return IntroFragment2.newInstance();
            }
        }


        @Override
        public int getCount() {
            return 2;
        }

    }
}

Upvotes: 1

Views: 517

Answers (1)

Aman
Aman

Reputation: 147

SOLVED BY @MikeM. in the comments above.

Since I was already using a ViewPager, All that was required was to give the correct item number to my ViewPager.

int THE_POSITION_OF_THE_FRAGMENT_IN_VIEW_PAGER = 1;
mViewPager.setCurrentItem(THE_POSITION_OF_THE_FRAGMENT_IN_VIEW_PAGER);

Upvotes: 1

Related Questions