Replacing fragments within viewpager

前端 未结 2 760
再見小時候
再見小時候 2021-01-27 11:27

I am currently having an issue with replacing a certain fragment within ViewPager with another. The fragment id like to replace is my \"Departments\" which has an Imagebutton id

2条回答
  •  后悔当初
    2021-01-27 11:58

    I think the point is to use a fragment as a container.

    In your ViewPagerAdapter:

        @Override
        public Fragment getItem(int position) {
            /*
             * IMPORTANT: This is the point. We create a RootFragment acting as
             * a container for other fragments
             */
            if (position == 0)
                return new RootFragment();
            else
                return new StaticFragment();
        }
    

    RootFragment layout should look like:

    
    
    

    And directly, you fill it with your first "real" fragment:

    public class RootFragment extends Fragment {
    
    private static final String TAG = "RootFragment";
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        /* Inflate the layout for this fragment */
        View view = inflater.inflate(R.layout.root_fragment, container, false);
    
        FragmentTransaction transaction = getFragmentManager()
                .beginTransaction();
        /*
         * When this container fragment is created, we fill it with our first
         * "real" fragment
         */
        transaction.replace(R.id.root_frame, new FirstFragment());
    
        transaction.commit();
    
        return view;
    }
    }
    

    Finally, you can replace fragments. For instance, inside your "real" fragment you could have a button:

    btn.setOnClickListener(new OnClickListener() {
    
            @Override
            public void onClick(View v) {
                FragmentTransaction trans = getFragmentManager()
                        .beginTransaction();
                /*
                 * IMPORTANT: We use the "root frame" defined in
                 * "root_fragment.xml" as the reference to replace fragment
                 */
                trans.replace(R.id.root_frame, new SecondFragment());
    
                /*
                 * IMPORTANT: The following lines allow us to add the fragment
                 * to the stack and return to it later, by pressing back
                 */
                trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                trans.addToBackStack(null);
    
                trans.commit();
            }
        });
    

    I've developed an example application that shows a similar concept. You could replace a fragment inside a ViewPager without changing to a new Activity. The code is available in:

    https://github.com/danilao/fragments-viewpager-example

提交回复
热议问题