简体   繁体   中英

Replace old fragment to add new fragment inside viewpager

I have this code. in setting fragment i had button when click that button i want to view new fragment.

public class TabsPagerAdapter extends FragmentPagerAdapter {

public TabsPagerAdapter(FragmentManager fm) {
    super(fm);

}

@Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
Log.i("TAB", "Home");
return new HomePage();
case 1:
// Games fragment activity
Log.i("TAB", "Contact");
return new GetContacts();
case 2:
// Movies fragment activity
Log.i("TAB", "Setting");
return new Settings();
}
return null;
}

i extends FragmentPageAapter.

okay here is how to add button in fragment A to switch fragment c : 1- add button in Fragment a in xml file which id foo like this :

<Button
    android:id="@+id/foo"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="go to fragemnt c" />

go to fragment a class overide method called onCreateView and set onclickListner create by creating interface called it buttonClick and create var from it in side fragment a then override method onAttch initialize interface var inside onAttch method:

public class FragmentA extends Fragment {

buttonClick click;
Button foo;

interface buttonClick {
    void buttonClicked(View v);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    click = (buttonClick) activity;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_a, container,false);

    foo = (Button) view.findViewById(R.id.foo);
    foo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            click.buttonClicked(v);
        }
    });

    return view;
}

}

then back to your MainActivity implements buttonClick interface and override methods in the method called buttonClicked(View v); setCurrentItem for view pager like this :

calss MainActivity implements FragmentA.buttonClick {

   // your code here ...

   public void buttonClicked(View v){
      //get your viewPager var
      viewPager.setCurrentItem(3);
    }

}

i hope this helps

Well you have multiple ways of achieving your "i want to view new fragment".

By "new fragment" you could mean "new content and ui" if that's so, you could "cheat" your way out and inflate a layout with overlaying views, that you set to VISIBLE or GONE .

Eg

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content" >

   <LinearLayout
       android:id="@+id/lyt_stuff_a"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content" >

       <TextView
           android:id="@+id/txt_stuff_a"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="This stuff is for content a" />
   </LinearLayout>

   <LinearLayout
       android:id="@+id/lyt_stuff_b"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content" >

       <TextView
           android:id="@+id/txt_stuff_b"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="This stuff is for content b"
           android:visibility="gone" />
   </LinearLayout>

</RelativeLayout>

So in code you just switch your content by

getView().findViewById(R.id.lyt_stuff_a).setVisibility(View.GONE);
getView().findViewById(R.id.lyt_stuff_b).setVisibility(View.VISIBLE);

But this approach might bloat your View tree, if your layout is very complex. And also the appropriate Fragment might do too much stuff, that you would like to separate in multiple Fragments.

If that's the case, you have to be aware of configuration changes or restarts of your App and handle those changes (ie save your state and reinitialize the right Fragments). If you are ok with that, you can change Fragments inside a ViewPager during runtime:

public class TabsPagerAdapter extends FragmentPagerAdapter {

    protected Fragment[] fragments;

    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
        initFragPageCount();
    }

    private void initFragPageCount() {
        fragments = new Fragment[3];
    }

    @Override
    public int getCount() {
        return fragments.length;
    }

    @Override
    public Fragment getItem(int position) {
        Fragment f = fragments[position];
        if (f == null) {
            f = initFragment(position);
        }
        return f;
    }

    private Fragment initFragment(int position) {
        Fragment f = fragments[position];
        if (f == null) {
            switch (position) {
            case 0:
                f = new HomePage();
                fragments[position] = f;
                break;
            case 1:
                f = new GetContacts();
                fragments[position] = f;
                break;
            case 2:
                f = new Settings();
                fragments[position] = f;
                break;
            }
        }
        return f;
    }

    public void replaceFrag(Fragment f, int index) {
        if (index > 0 && index < fragments.length) {
            fragments[i] = f;
        }
        notifyDataSetChanged();
    }
}

You can replace it like this (eg in your Button's OnClickListener ):

adaptPager.replaceFrag(new FragReplacement(), 2); // replaces the third Fragment in the Pager

add or remove fragment in viewpager dynamically.
To load different fragment call setupViewPagerCustom(viewPager). eg on button click call: setupViewPagerCustom(viewPager);

    private void setupViewPager(ViewPager viewPager)
{
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new fragmnet1(), "HOME");
    adapter.addFrag(new fragmnet2(), "SERVICES");

    viewPager.setAdapter(adapter);
}

private void setupViewPagerCustom(ViewPager viewPager)
{

    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

    adapter.addFrag(new fragmnet3(), "Contact us");
    adapter.addFrag(new fragmnet4(), "ABOUT US");


    viewPager.setAdapter(adapter);
}

//Viewpageradapter, handles the views

static class ViewPagerAdapter extends FragmentStatePagerAdapter
{
    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();
    }

    @Override
    public int getItemPosition(Object object){
        return PagerAdapter.POSITION_NONE;
    }

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

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

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