How restart Fragment in my Activity - Android

2019-06-14 17:56发布

I have an activity that have 3 fragment inside. I need restart a first fragment in my activity with click on Button.

ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new HomeFragment(), "Home");
adapter.addFrag(new CategoryFragment(), "Category");
adapter.addFrag(new FilterFragment(), "Filter");
viewPager.setAdapter(adapter);

I test the following way but doesn't work and show error: refresh fragment at reload

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.setNextAnim(int)' on a null object reference 

2条回答
别忘想泡老子
2楼-- · 2019-06-14 18:13

On button click you check if the current position of your ViewPager is bigger than 0 (first position) and set it to the first position, like this:

if(viewPager.getCurrentItem>0){
  viewPager.setCurrentItem(0);
}
查看更多
仙女界的扛把子
3楼-- · 2019-06-14 18:19

You can reload your fragment with this:

FragmentTransaction tr = getFragmentManager().beginTransaction();
tr.replace(R.id.fragment_layout, instanceFragment);
tr.commit()

Being instanceFragment the instance of the fragment you wanna to reload and fragment_layout the FrameLayout component in your activity layout XML file.

查看更多
登录 后发表回答