简体   繁体   中英

Run new fragment instance with viewpager on click on menu item

I have a working fragment code based on Android Studio's "Tabbed Activity" project structure. However, since I have dynamically created content filling the space, the standard swipe isn't applicable and I'd like to toggle between fragments when selecting an item from a menu.

This is my code for the fragments:

private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;

public static class PlaceholderFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    public static PlaceholderFragment newInstance(int sectionNumber)
    {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup containerPager,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, containerPager, false);
        TextView textView = (TextView) rootView.findViewById(R.id.temporary);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

// FRAGMENT 1 - First. This one should have a blank layout!
public static class FragmentFirst extends Fragment {
    public static FragmentFirst newInstance(int sectionNumber) {
        FragmentFirst fragment = new FragmentFirst();
        return fragment;
    }

    public FragmentFirst() { }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup containerPager,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_first, containerPager, false);
        return rootView;
    }
}

// FRAGMENT 2 - Second
public static class FragmentSecond extends Fragment {
    public static FragmentSecond newInstance(int sectionNumber) {
        FragmentSecond fragment = new FragmentSecond();
        return fragment;
    }

    public FragmentSecond() { }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup containerPager,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, containerPager, false);
        return rootView;
    }
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).

        switch (position) {
            case 0:
                return FragmentFirst.newInstance(position + 1);
            case 1:
                return FragmentSecond.newInstance(position + 1);
            default:
                //assume you only have 2
                throw new IllegalArgumentException();
        }
    }

    @Override
    public int getCount() {
        // Show 2 total pages.
        return 2;
    }
}

OnCreate:

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

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    ViewPager mViewPager = (ViewPager) findViewById(R.id.containerPager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
}

Furthermore, here is the code for choosing the particular menu item:

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.change_fragment)
    {

        // Can I run/initiate the code at public Fragment getItem(int position) {} 
        // from here?

        // The lines below do work, but rather than running the fragments' code,
        // it simply overlaps with the current content.

        ViewPager mViewPager = (ViewPager) findViewById(R.id.containerPager);
        mViewPager.setCurrentItem(1, true);

        return true;
    }
    return super.onOptionsItemSelected(item);
}

I am familiar with mViewPager.setCurrentItem(position, true) , however, rather than applying the fragment over the current layout, I'd like to trigger the fragment code so it can change between layouts - in this case, to fragment_main , or FragmentSecond .

Problem:

Is it possible to run the code in public Fragment getItem(int position) {} outside its class SectionsPagerAdapter extends FragmentPagerAdapter ? Or is there a better way to achieve what I'm looking for?

public Fragment getItem(int position) {
        switch(position)
        {
            case 0:

                FragmentMain tab1 = new FragmentMain ();
                return tab1;

            case 1:

                FragmentSecond tab2 = new FragmentSecond ();
                return tab2;




            default:

                return null;
        }

i use this to switch fragments

XML :

<?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:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:background="@color/colorPrimary"
            app:tabGravity="fill"
            app:tabIndicatorColor="@color/black"
            app:tabMode="fixed"
            app:tabSelectedTextColor="@color/black"
            app:tabTextAppearance="@style/buttonThemePrimaryHolo1"
            app:tabTextColor="#fff" />

        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/tabs">

        </android.support.v4.view.ViewPager>

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

In Activity :

TabLayout tabLayout;
ViewPager viewPager;


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

        viewPager = findViewById ( R.id.viewpager );
        setupViewPager ( viewPager );

        tabLayout = findViewById ( R.id.tabs );
        tabLayout.setupWithViewPager ( viewPager );

}
private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter ( getSupportFragmentManager () );
        adapter.addFragment ( new Fragment1 (), "Fragment1 " );
        adapter.addFragment ( new Fragment2 (), "Fragment2 " );
        adapter.addFragment ( new Fragment3 (), "Fragment3 " );
        adapter.addFragment ( new Fragment4 (), "Fragment4 " );
        viewPager.setAdapter ( adapter );
}

class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List <Fragment> mFragmentList = new ArrayList <> ();
        private final List <String> mFragmentTitleList = new ArrayList <> ();

        public ViewPagerAdapter(FragmentManager manager) {
            super ( manager );
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get ( position );
        }

        @Override
        public int getCount() {
            return mFragmentList.size ();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add ( fragment );
            mFragmentTitleList.add ( title );
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get ( position );
        }
    }            

In Fragment

private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter ( getChildFragmentManager() );
        adapter.addFragment ( new Fragment1 (), "Fragment1 " );
        adapter.addFragment ( new Fragment2 (), "Fragment2 " );
        adapter.addFragment ( new Fragment3 (), "Fragment3 " );
        adapter.addFragment ( new Fragment4 (), "Fragment4 " );
        viewPager.setAdapter ( adapter );
}    

Other part are same as activity in fragment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM