How restart Fragment in my Activity - Android

匿名 (未验证) 提交于 2019-12-03 00:46:02

问题:

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 

回答1:

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.



回答2:

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); }


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