I have a tab layout with 2 fragment and I have a toolbar with different options that belong to the activity which hosts the view pager.
When I click on a toolbar option, it clean the data from DB that are used in the fragment and then it should refresh it to apply changes at screen.
But I can't find a way to refresh the fragment from the activity.
Here is the fragment adapter :
public class FragmentAdapter extends FragmentPagerAdapter
{
private final List<Fragment> lstFragment = new ArrayList<>();
private final List<String> lstTitles = new ArrayList<>();
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return lstFragment.get(i);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return lstTitles.get(position);
}
#Override
public int getCount() {
return lstTitles.size();
}
public void AddFragment (Fragment fragment , String title)
{
lstFragment.add(fragment);
lstTitles.add(title);
}
}
Here is the way I call it in the fragments in main :
FragAdapter = new FragmentAdapter(getSupportFragmentManager());
((FragmentAdapter) FragAdapter).AddFragment(new FragmentProgramme(),"Programmes");
((FragmentAdapter) FragAdapter).AddFragment(new FragmentPlanning(),"Agenda"); //FRAGMENT I WANT TO REFRESH
mviewpager.setAdapter(FragAdapter);
mtablayout = (TabLayout) findViewById(R.id.main_tabs);
mtablayout.setupWithViewPager(mviewpager);
In the main, I have the option on the toolbar and I would like to do something like this :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int pos = item.getItemId();
switch (pos)
{
DatabaseAgenda.getInstance(this).dropDB(); //CLEAN DB
// I would like to find a function like this : ((FragmentAdapter) FragAdapter).refresh(FragmentPlanning, "Agenda");
break;
}
return super.onOptionsItemSelected(item);
}
The point is to simply destroy the fragment because all the data must be cleaned from screen and then recreate it so the users can add new data to it
I hope this is clear, thank you for your hlelp
I have found a lot answers but never what I was really looking for
You can override the method setUserVisibleHint inside fragments to detect when it is visible. Data can be refreshed inside this method. Selecting the items of pageradapter programatically triggers setUserVisibleHint of present fragment. You would not need destroying fragments each time.
When my Activity gets recreated via orientation change or if "Don't keep activities" is turned on in developer settings, my ViewPager that has
FragmentStatePagerAdapter doesn't recreate fragments.
this is activity onCreate method:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
AndroidInjection.inject(this);
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
pagerAdapter = new CustomPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
viewPager.addOnPageChangeListener(this);
presenter.onCreate();
}
this is FragmentStatePager:
public class CustomPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments = new ArrayList<>();
public MyFoodaPagerAdapter(FragmentManager fm) {
super(fm);
}
public void init(List<Fragment> initFrags) {
fragments.addAll(initFrags);
notifyDataSetChanged();
}
public void update(Fragment fragment, int position) {
fragments.set(position, fragment);
notifyDataSetChanged();
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getItemPosition(Object object) {
if (!fragments.contains(object)) {
return POSITION_NONE; // replace
}
return super.getItemPosition(object);
}
public void clear(){
fragments.clear();
notifyDataSetChanged();
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return "Title "+position; // TODO: 25/10/2017
}
}
Since FragmentStatePagerAdapter saves currently selected fragment and the one's right next to it, if I only have 2 fragments in pager and Activity gets recreated, changing fragment list and calling notifyDataSetChanged(); doesn't do anything.
getItem(int position) doesn't get triggered in PagerAdapter at all after activity gets recreated. If I have 3+ fragments in the pager and 1st one is selected then moving to 3rd page will render that fragment and moving back to 1st fragment will finally render 1st fragment. If I have only 2 fragments in pager then moving between does nothing, they do not get rendered.
Also what I'm seeing after Activity is recreated. FragmentManager has those 2 fragments with reference numbers lets say (Fragment1#1000) and (Fragment2#1001), when I add new fragments into private List<Fragment> fragments, (Fragment1#1050) and (Fragment2#1051) in pager adapter and call notifyDataSetChanged(), fragmentManager does not update its fragments, it will still have those old fragments in.
EDIT: I think I found my problem support FragmentPagerAdapter holds reference to old fragments
Which says in short, even in the comments, is to never hold reference to fragments outside of PagerAdapter.
Please use this code to update the Fragment View when you are moving between Fragments whether its two or more than that.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
getFragmentManager().beginTransaction().detach(this).attach(this).commit();
//getPlanListData();
}
}
I have a ViewPager with 3 tabs.
I'm loading big data in every fragments.
The app load every fragments but I want to load fragment only when its selected.
How can I do that? I have no idea.
I'm waiting for your help. Thank you
my code:
public class Fragments extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_tabs);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstFragment(), "1");
adapter.addFragment(new SecondFragment(), "2");
adapter.addFragment(new ThirdFragment(), "3");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
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();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
If no one has given you a good answer I know this is 5 years later, but anyone reading this. I'm actually having the opposite problem. I need to load all tabs at the same time. What is happening to me now is only one tab is loading at a time. I need to use this adapter for viewpager2 with tablayout so that I can disable the viewpager swiping left to right for my specific usecase.
Here is my code:
WARNING CODE IS IN KOTLIN NOT JAVA
class RecipeTabAdapter internal constructor(fm: FragmentManager, lifecycle: Lifecycle) : FragmentStateAdapter(fm, lifecycle) {
val fragmentsList: ArrayList<Fragment> = arrayListOf()
fun addFragment(fragment: Fragment) {
fragmentsList.add(fragment)
}
override fun getItemCount(): Int {
return fragmentsList.size
}
override fun createFragment(position: Int): Fragment {
when (position) {
position -> fragmentsList[position]
position -> fragmentsList[position]
}
return fragmentsList[position]
}
}
Is it possible to disable the offscreen page limit?
No. It is already set to the minimum possible value: one page to each side of the viewed page. This is necessary to have the animation effects work -- you see parts of two fragments (original and new) at the same time.
In
OncreateView(){
//.... dont initialize your view here
if(isMenuVisible()) { // menu should be visible if current fragment is visible right now
setUserVisibleHint(true); // manually set value to true
}
}
in
oncreate(){
setHasOptionsMenu(true);
}
Finally there is method called setuservisiblehint() which is only called when the fragment is visible to the user this is the only method where you shud initialize all your views.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser && v != null) {
// initialize your view here and call you fetch_data_function()
}
Here's my solution and it works as expected. In all of your child fragments create a boolean variable:
private boolean loadFragmentExecuted = false;
in the child fragments create a generic method called loadFragment and move all of the logic you added in onCreateView to that method:
public void loadFragment()
{
if(!loadFragmentExecuted)
{
//Add your logic to manipulate the UI or load data etc...
loadFragmentExecuted = true;
}
}
in your pageview logic create the fragments dynamically like:
//add the fragment
String fragmentName = "com.something." + fragmentId;
//check if the class exists
try
{
Class myFragmentClass = Class.forName(fragmentName);
Fragment myFragment = (Fragment) myFragmentClass.newInstance();
mFragments.add(myFragment);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
then set your pager adapter and attach a tablayout with it:
//set our pager adapter that contains different fragments
mPagerAdapter = new BasePagerAdapter(mFragmentManager, mFragments);
//link the adapter to the viewpager
mViewPager.setAdapter(mPagerAdapter);
//cache fragments
int limit = (mPagerAdapter.getCount() > 0 ? mPagerAdapter.getCount() : 1);
mViewPager.setOffscreenPageLimit(limit);
//add the page listner to the viewPager and link it to the tabLayout
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
//on tab selected select current viewpager item
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
#Override
public void onTabSelected(TabLayout.Tab tab)
{
mViewPager.setCurrentItem(tab.getPosition());
//get fragment for the selected tab
Fragment f = mPagerAdapter.getItem(tab.getPosition());
//load the content of the fragment
try
{
Class c = f.getClass();
Method loadFragment = c.getMethod("loadFragment");
loadFragment.invoke(f);
}
catch (IllegalAccessException e){}
catch (InvocationTargetException e){}
catch (NoSuchMethodException e){}
}
#Override
public void onTabUnselected(TabLayout.Tab tab)
{
}
#Override
public void onTabReselected(TabLayout.Tab tab)
{
}
});
I have a solution that does not require subclassing, and it's easy to introduce into existing projects. It uses the child fragment mechanism.
The basic idea is to replace your content fragment with an almost empty fragment, and add your content fragment as a child fragment when it is really visible to the user
The gist of the code is like this
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
boolean hasFragment = getChildFragmentManager().findFragmentById(R.id.container) != null;
if (hasFragment) {
return;
}
if (getUserVisibleHint()) {
addFragment("onViewCreated");
}
}
#Override
public void onResume() {
super.onResume();
if (getUserVisibleHint()) {
addFragment("onResume");
}
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) {
addFragment("setUserVisibleHint");
}
}
private void addFragment(String cause) {
if (getChildFragmentManager().findFragmentById(R.id.container) == null) {
getChildFragmentManager().beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.add(R.id.container, createFragment()).commit();
}
}
Check out my full solution here, which also contains a progressbar, and the option to automatically start loading of background fragments with a specified delay: Lazy Load Fragment
Hi, to all!
I have a problem with the TabMenu, below i've posted a GIF, which shows how it works, it doesn't work correctly.
How it works in code:
MainActivity(ViewPager, TabsLayout)->FragmnetAdapter(For tabs layout)
How its must be: "Home"(HomeFragment), "History"(HistoryFragment), "Places"(PlacesFragment)
Now when its start at "Home" start "Home" but and call "History" on "Hstory" call "Places"
But in code i didnt see some problems can you help me, please:)
Here is the code:
MainActivity:
public class MainActivity extends AppCompatActivity {
#BindView(R.id.appToolbarMainTabs)
Toolbar appToolbar;
#BindView(R.id.tabLayoutTabs)
TabLayout tabs;
#BindView(R.id.viewPager)
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(appToolbar);
setupViewPager(viewPager);
tabs.setupWithViewPager(viewPager);
}
// Add Fragments to Tabs
private void setupViewPager(ViewPager viewPager) {
FragmentTabsAdapter adapter = new FragmentTabsAdapter(getSupportFragmentManager());
adapter.addFragment(new HomeFragment(), getString(R.string.home_tab));
adapter.addFragment(new HistoryFragment(), getString(R.string.history_tab));
adapter.addFragment(new PlacesFragment(), getString(R.string.places_tab));
viewPager.setAdapter(adapter);
}}
FragmentAdapter:
public class FragmentTabsAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public FragmentTabsAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}}
Home&History&PlaceFragment don't needed i think so:)
Thanks a lot!:)
The tabs and the ViewPager are ok, it always preloads at least the previous and the next fragments.
You could only show the dialog when the fragment is shown and it is still loading the info.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
if (fragmentIsLoadingInfo()) { // implement this
showLoading(); // implement this
}
}
}
Also check the setOffscreenPageLimit of a ViewPager to understand what is happening and to update this value if you, for example, want all the three fragments to load at once. Its a shame that if you set it to 0 it still works as if it was 1.
The fragments I use in my ViewPager instance are quite resource intensive, so I'd only like to load one at a time. When I try the following:
mViewPager.setOffscreenPageLimit(0);
mViewPager.setAdapter(mPagerAdapter);
My FragmentStatePagerAdapter.getItem(int position) override function is called 3 times, which is what happens when I call mViewPager.setOffscreenPageLimit(1). I would expect it to only be called once, because I specified 0 offscreen pages.
I believe I'm calling everything correctly, because if I call mViewPager.setOffscreenPageLimit(2), FragmentStatePagerAdapter.getItem(int position) is called 5 times as I would expect.
Does ViewPager require a minimum of 1 offscreen pages, or am I doing something wrong here?
The best way that I found was setUserVisibleHint
add this to your fragment
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// load data here
}else{
// fragment is no longer visible
}
}
Does ViewPager require a minimum of 1 offscreen pages
Yes. If I am reading the source code correctly, you should be getting a warning about this in LogCat, something like:
Requested offscreen page limit 0 too small; defaulting to 1
You can try like this :
public abstract class LazyFragment extends Fragment {
protected boolean isVisible;
/**
* 在这里实现Fragment数据的缓加载.
* #param isVisibleToUser
*/
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(getUserVisibleHint()) {
isVisible = true;
onVisible();
} else {
isVisible = false;
onInvisible();
}
}
protected void onVisible(){
lazyLoad();
}
protected abstract void lazyLoad();
protected void onInvisible(){}
protected abstract void lazyLoad();
protected void onInvisible(){}
First Add
boolean isFragmentLoaded = false;
than
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && !isFragmentLoaded) {
//Load Your Data Here like.... new GetContacts().execute();
isFragmentLoaded = true;
}
else{
}
}
this may be old thread but this seems to work for me. Override this function :
#Override
public void setMenuVisibility(boolean menuVisible) {
super.setMenuVisibility(menuVisible);
if ( menuVisible ) {
/**
* Load your stuffs here.
*/
} else {
/**
* Fragment not currently Visible.
*/
}
}
happy codings...
ViewPager is default to load the next page(Fragment) which you can't change by setOffscreenPageLimit(0). But you can do something to hack.
You can implement onPageSelected function in Activity containing the ViewPager. In the next Fragment(which you don't want to load), you write a function let's say showViewContent() where you put in all resource consuming init code and do nothing before onResume() method. Then call showViewContent() function inside onPageSelected. Hope this will help.
in my case i wanted to start some animations in views, but with setUserVisibleHint got some issues ...
my solution is :
1/ addOnPageChangeListener for your adapter :
mViewPager.addOnPageChangeListener(this);
2/ implement OnPageChangeListener :
public class PagesFragment extends Fragment implements ViewPager.OnPageChangeListener
3/ override the 3 methodes :
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
#Override
public void onPageSelected(int position)
{
}
#Override
public void onPageScrollStateChanged(int state)
{
}
4/ declare and initialize this variable on your class
private static int mTabState = 1;
notice : i have three fragments in my adapter, and use mTabState for setCurrentItem and current position of adapter which recognize which fragment is show to user in time ...
5/ in onPageSelected method add this codes :
if (mTabState == 0 || position == 0)
{
Intent intent = new Intent("animation");
intent.putExtra("current_position", position);
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
}
if previous page or current page is page 0(fragment in position 0) then do this stuff
6/ now in your fragment class (fragment in position 0 of adapter), you must create broadcast receiver and register it in onResume method and unregister it onPause methos :
BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
if (Objects.equals(intent.getAction(), "animation"))
{
int currentPosition = intent.getIntExtra("current_position", 0);
if (currentPosition == 0)
{
startAnimation();
setViewsVisible();
} else
{
setViewsInvisible();
}
}
}
};
#Override
public void onResume()
{
super.onResume();
LocalBroadcastManager.getInstance(mContext).registerReceiver(broadcastReceiver, new IntentFilter("animation"));
}
#Override
public void onPause()
{
super.onPause();
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(broadcastReceiver);
}
summary : i have Fragment Pager Adapter witch shows Three Fragments in it, I want show some Animations on Views in Fragment in Position 0 of Adapter, For this I use BroadcastReceiver. When Fragment is Picked I start the Animation method and shows the Views to User, When Fragment is not Showing to User I try to Invisible Views...
View Pager With only one Page :
This is February 2021: I have able to add only one page with viewPager. The approach is with ViewPager, FragmentPagerAdapter, Tablayout, and a fragment. In my case, I can populate many Pages with many tabs, or only one Page with one Tab. When one tab and one page, on swipe left or right, I can manage to change the chapter of my document (which I want to show next). And when many pages and many tabs, I can change the entire book of documents.
In main Activity Oncreate: (Here is my working code approach, I have changed nothing here from my working code):
if(getIntent()!=null){
if(getIntent().getStringExtra("ONLY_TAFHEEM")!=null)
sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager(), suraName, suraId, ayatId, true);
else
sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager(), suraName, suraId, ayatId, false);
}else {
sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager(), suraName, suraId, ayatId, false);
}
final ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
tabsLayout = findViewById(R.id.tabs);
tabsLayout.animate();
tabsLayout.setupWithViewPager(viewPager);
In Adapter :
#NonNull
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.sendData(mContext, postion, suraName, suraId, ayahId, ARABIC_AYAH, BENGALI_AYAH, actualDbNames[position], tafsirDisplayNames[position]);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return tafsirDisplayNames[position];
}
#Override
public int getCount() {
// this is the tricky part // Show pages according to array length. // this may only one // this is the tricky part :
return tafsirDisplayNames.length;
}
And at last the fragments public constructor :
public static PlaceholderFragment sendData(Context mContext, int tabIndex, String suraName, String suraId, String ayahNumber, String arabicAyah, String bengaliAyah, String actualDbName, String displayDbName) {
Log.i("PlaceHolder", "Tafhim sendData: " + bengaliAyah);
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle bundle = new Bundle();
mContext_ = mContext;
BENGALI_AYAH = bengaliAyah;
_DISPLAY_DB_NAME = displayDbName;
bundle.putInt(ARG_SECTION_NUMBER, tabIndex);
bundle.putString(SURA_NAME, suraName);
bundle.putString(SURA_ID, suraId);
bundle.putString(AYAH_NUMBER, ayahNumber);
bundle.putString(ARABIC_AYAH, arabicAyah);
bundle.putString(ACTUAL_DB_NAME, actualDbName);
bundle.putString(DISPLAY_DB_NAME, displayDbName);
fragment.setArguments(bundle);
return fragment;
}
That's all, just passing the array (of Tab Labels) to the adapter, (it may only one element, in case, for one page), with my need, I can populate one page or more page, and according to this it populate one tab or many tabs : in the above code the array is: tafsirDisplayNames. I can also create the array manually in adapter, when the adapter first called, Or, recreate the array with +-elements, on recreate the MainActivity.
Please Try This Code for resolve issue of refreshing view in Viewpager....
/* DO NOT FORGET! The ViewPager requires at least “1” minimum OffscreenPageLimit */
int limit = (mAdapter.getCount() > 1 ? mAdapter.getCount() - 1 : 1);
mViewPager.setOffscreenPageLimit(limit);
for the "instantiateItem" function, just prepare the fragment, but don't load the heavy content.
Use "onPageChangeListener" , so that each time you go to a specific page, you load its heavy content and show it.
I kind of have the same problem. I found some useful code on this site and transform it.
The min int for mViewPager.setOffscreenPageLimit(...); is 1, so even if you change it to 0 you will still have 2 pages loaded.
First thing to do is to create a static int we will call maxPageCount and override FragmentStatePagerAdapter method getCount() to return maxPageCount:
#Override
public int getCount() {
return maxPageCount;
}
Create then a static method accessible from any where in the program that will allow you to change this maxCount:
public static void addPage(){
maxPageCount++; //or maxPageCount = fragmentPosition+2
mFragmentStatePagerAdapter.notifyDataSetChanged(); //notifyDataSetChanged is important here.
}
Now initialize maxPageCount to 1. When ever you want you can add another page.
In my case when I needed the user to treat the current page first before generated the other. He do it and then, without problem can swipe to the next page.
Hope it help someone.
Use This
// create boolean for fetching data
private boolean isViewShown = false;
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getView() != null) {
isViewShown = true;
// fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
fetchData();
} else {
isViewShown = false;
}
}
// step 1: add BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT FragmentPagerAdapter contractor
public class BottomTabViewPager extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public BottomTabViewPager(FragmentManager manager) {
super(manager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void addTabs(String title) {
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
// return null;
}
}
// step 2: You can try like this :
public class MyFragment extends Fragment {
public MyFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_ui, container, false);
return view;
}
#Override
public void onResume() {
super.onResume();
/**
* Load your stuffs here.
*/
}
}