4

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 
Arman Download
  • 174
  • 1
  • 2
  • 14
  • this way doesn't work an show error: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.Fragment.setNextAnim(int)' on a null object reference – Arman Download Oct 27 '17 at 19:43

3 Answers3

5

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.

GuilhermeFGL
  • 2,891
  • 3
  • 15
  • 33
  • what is "your_fragment_container" and "yourFragmentInstance"? – Arman Download Oct 27 '17 at 19:37
  • `yourFragmentInstance` is the new instance of the fragment you wanna to reload, in your case, the first one; `your_fragment_container` is the `FrameLayout` in your XML layout file. I have updated my answer – GuilhermeFGL Oct 27 '17 at 19:44
  • for anyone looking for a method to reload a fragment without facing an `IllegalStateException` use the code described above in the fragments' host activity – Khalid ElSayed Oct 28 '17 at 16:58
4

For Android SDK >= 21 you may use this approach:
In your Activity class add function restartFragment

fun restartFragment(fragmentId: Int) {
    val currentFragment = this.supportFragmentManager.findFragmentById(fragmentId)!!

    this.supportFragmentManager.beginTransaction()
        .detach(currentFragment)
        .commit()
    this.supportFragmentManager.beginTransaction()
        .attach(currentFragment)
        .commit()
}

In your Fragment call

(requireActivity() as <YourActivityClassName>).restartFragment(id, R.id.<your_fragment_id>)

Personally I took R.id.<your_fragment_id> from my nav_graph as R.id.settings_fragment and as MainActivity

Emir Vildanov
  • 71
  • 2
  • 3
0

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);
}
Natan Felipe
  • 173
  • 1
  • 5