Change viewpager fragment by a buttonClick

倖福魔咒の 提交于 2019-11-30 07:18:59

I'm not sure what exactly you said about "Change".

If you're asking about change page display index, you can try

ViewPager.setCurrentItem(int pageIndex, boolean isSmoothScroll);

Or, if you're asking about change content, here's what I did

public class MyPagerAdapter extends FragmentStatePagerAdapter
{
  private FragmentManager fragMan;
  private ArrayList<Fragment> fragments=new ArrayList<Fragment>();

  public void clearAll() //You can clear any specified page if you want...
  {
    for(int i=0; i<fragments.size(); i++)
    fragMan.beginTransaction().remove(fragments.get(i)).commit();
    fragments.clear();
    fragments=new ArrayList<Fragment>();
    notifyDataSetChanged();
  }

  public void addList() //Add some new fragment...
  {
    listFrag=new ListFragment();
    fragments.add(list);
  }
}

Hope it helps~

Sébastien BATEZAT

I'm posting a new answer because - from what I can see - the real answer is on the comment of the accepted answer:

"You have 2 way to do. 1) Put your ViewPager object as public static, so that you can access in any of your Fragment. 2) Stay your ViewPager in as member of your FragmentActivity, send a broadcast intent from your Fragment to FragmentActivity, and access your ViewPager object. – RRTW May 28 '13 at 2:18 "

So thanks to RRTW for that answer, but I would like to improve it.

1) is NOT an option. The purpose of fragments is to be reusable, so they need to be independant from the Activity. Linking them to activity is I think a bad practise, even if - for now - you are not re-using it on other activity.

2) Sounds very good, but I think it needs more explanation. The purpose of getAcitivty().sendBroadcast() is to send an event to all application of the user's system. It's definitly not what you want to achieve. So the good answer, from my point of view, is to use LoacalBroadcastManager, and you can have a look on that post to understand how to use it.

In main just call make your Viewpager public so its accessable from other java files( ex. from frag1.java)

MainActivity.Java:

public static ViewPager pager;

Now, in the Onclick() function inside frag1.java just call your mViewPager and set the item(fragment) to whatever fragment you want to load. Ex. If you want to load the next fragment then you set it to 2.

frag1.java

public void onClick(View v) {

    ViewPager.setCurrentItem(2);

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!