PagerSlidingTabStrip - add new tab at run time - android

I am using PagerSlidingTabStrip to show 3 tabs, with each containing list view in it.
I have a scenario where i need to add new tab at runtime, say on swipe to refresh i need to add new tab to the left end.
Below is my code to add new tab :
pagerAdapter.TABS_COUNT = 4; //global value to change the tabs count
pagerAdapter.notifyDataSetChanged();
pagerSlidingTabStrip.setViewPager(mPager);
but some times one of the tabs content becomes empty listview is not scrollable.
What is the best way that i can achieve this ?

Here is an example on how to do it, don't say it's the best way, but I wrote it in hurry https://github.com/jacktech24/pager-sliding-strip-example
First, you will need a custom adapter, here I used a simple one which is displaying only text on each fragment, but it would be easy to modify it to support normal fragments etc. mTabs in the example is:
mTabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
then the example
private class TestAdapter extends FragmentPagerAdapter {
private ArrayList<String> tabs = new ArrayList<>();
public TestAdapter(FragmentManager supportFragmentManager) {
super(supportFragmentManager);
}
#Override
public Fragment getItem(int position) {
Fragment frag = new ExampleFragment();
Bundle bundle = new Bundle();
bundle.putString("title", (String) getPageTitle(position));
frag.setArguments(bundle);
return frag;
}
#Override
public CharSequence getPageTitle(int position) {
return tabs.get(position);
}
#Override
public int getCount() {
return tabs.size();
}
public void addTab(String tab) {
tabs.add(tab);
notifyDataSetChanged();
mTabs.notifyDataSetChanged();
}
public void removeTab(int position) {
tabs.remove(position);
notifyDataSetChanged();
mTabs.notifyDataSetChanged();
}
}
then, it is just as simple as this:
//mAdapter is instance of your adapter
mAdapter.addTab("test 1");
mAdapter.addTab("test 2");
mAdapter.addTab("test 3");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAdapter.addTab("test "+(mAdapter.getCount()+1));
}
});

Related

Same fragment called multiple time in ViewPager

I have a View pager. The user can choose how many differents pages he can have.
The pages are all the same layout but it will just load different data.
Here is my 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);
}
}
And here is the code to call the fragment multiple time :
FragAdapter = new FragmentAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.main_tabs_pager);
toolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
tabLayout = (TabLayout) findViewById(R.id.main_tabs);
String[] Fragments = {"Frag1", "Frag2", "Frag3", "Frag4"};
for (int i=0; i<Fragments.length; i++)
{
((FragmentAdapter) FragAdapter).AddFragment(new MenuFragment(),Fragments[i]);
}
viewPager.setAdapter(FragAdapter);
tabLayout = (TabLayout) findViewById(R.id.main_tabs);
tabLayout.setupWithViewPager(viewPager);
So it works fine. But the only problem is that I don't know how to know the difference in code between the differents fragments.
Exemple :
The frag1 must load 5 pictures about the sea
The frag2 must load 8 pictures about the sun
How can I tell the fragment what to do? I tried to pass in the constructeur the arguments by exemple
public MenuFragment(int numberofpictures, String picturesthemes)
{
// Required empty public constructor
}
but the constructors must be empty because it is not called again when fragment is destroyed and recreated...
does anyone has an idea? thanks
UPDATE
I don't know if that is the good way but here is the way I did it :
In main activity I created :
for (int i=0; i<Fragments.length; i++)
{
Bundle parameters = new Bundle();
parameters.putInt("myInt", i);
Fragment menuFragment = new MenuFragment();
menuFragment.setArguments(parameters);
((FragmentAdapter) FragAdapter).AddFragment(menuFragment, Fragments[i]);
}
Which give a everyfragment the the int i which is a reference to the title.
Then I simply wrote this function :
public String getName (int i)
{
return Fragments[i];
}
which return the title based on the int that the fragment got thanks to the bundle
Then, In the MenuFragment() I used this :
private void fillinthelist()
{
myInt = getArguments().getInt("myInt");
String test = ((MainActivity) getActivity()).getName(myInt);
ListOfProgrammes.add(new Modele_carte(test));
}
so it gets the int from the bundle and make a like to it thanks to the function in MainActivity
Is it the good way to do it? It seems to work
You can attach a Bundle containing the parameters with setArguments(Bundle) :
Bundle parameters = new Bundle();
parameters.putInt("myInt", <int_value>);
Fragment menuFragment = new MenuFragment();
menuFragment.setArguments(arguments);
((FragmentAdapter) FragAdapter).AddFragment(menuFragment, Fragments[i]);
A common practice is to build and attach the Bundle in a fragment's class static factory method.
The fragment can use getArguments() to retrieve the parameters.
private int myInt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myInt = getArguments().getInt("myInt");
}

How to select next tab from child fragment

I need to switch next tab, when a button is clicked from a child fragment.
This is how I setup tabs in parent,
TabAdapter adapter;
private void setUpTabs(ViewPager viewPager) {
adapter = new TabAdapter(getSupportFragmentManager());
adapter.addFragment(new FirstTabFragment(), "First Tab");
adapter.addFragment(new SecondTabFragment(), "Second Tab");
viewPager.setAdapter(adapter);
}
And my TabAdapter class is,
public class TabAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public TabAdapter(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);
}
}
I created a method to switch tab inside Parent
TabLayout myTabs= (TabLayout) findViewById(R.id.my_tabs);
Button chkBtn = (Button) findViewById(R.id.check_button);
chkBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(1);
}
});
Switching tabs inside parent class works fine. But how could I Do the same inside FirstTabFragment, Please help me.
You should call
viewPager.setCurrentItem(fragmentIdex);
you should use setCurrentItem(int item)
Set the currently selected page. `
sample code
chkBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewPager.setCurrentItem(2);
}
});
Just to make your UI more Interactive and good looking, I'm gonna share what I've implemented.
Just to access your viewPager from the fragment's java file, declare your viewPager as below in your parent activity.
public static ViewPager viewPager;
Then in the onClick method or onClickListener of a button in the fragment, you can just use this.
ParentActivity.viewPager.arrowScroll(View.FOCUS_RIGHT);
This will smooth scroll your viewpager to the Second Fragment, and yes, if you want to limit the user from scrolling directly you can disable the scrolling of viewPager, read here.
You can also shift the focus to left if user wants to go back to FirstFragment by just
ParentActivity.viewPager.arrowScroll(View.FOCUS_LEFT);
And yes, it's working as I first test before posting answers, silly me.

Changing tabs of TabLayout programmatically but fragments of ViewPager is not updated

I am developing an Android app. In my app, I am using TabLayout with ViewPager. I need to update the Tabs of TabLayout and its fragments programmatically when an item at the bottom navigation bar is selected. I can update the tabs of TabLayout. But the fragments of pager are not updated.
This is the issue:
As you can see in the above, tabs are changed but its fragments are not changed. List Fragment is always displayed. All the fragments are just the same with the first tab selected. I mean fragments are not changing at all.
This is my XML file for the tabs and view pager:
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/ma_tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:id="#+id/ma_viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
This is my whole activity:
public class MainActivity extends AppCompatActivity {
private BottomBar bottomBar;
private TabLayout topTabLayout;
private ViewPager mainViewPager;
private MainPagerAdapter pagerAdapter;
private ArrayList<Fragment> pagerFragments;
private ArrayList<String> pagerTitleList;
protected TfrApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (TfrApplication)getApplication();
setContentView(R.layout.activity_main);
initialize();
initViews();
setUpViews();
}
private void initialize()
{
pagerFragments = new ArrayList<Fragment>();
pagerTitleList = new ArrayList<String>();
}
private void initViews()
{
bottomBar = (BottomBar)findViewById(R.id.ma_bottom_action_bar);
mainViewPager = (ViewPager)findViewById(R.id.ma_viewpager);
topTabLayout = (TabLayout)findViewById(R.id.ma_tab_layout);
}
private void setUpViews()
{
pagerAdapter = new MainPagerAdapter(getSupportFragmentManager(),pagerFragments,pagerTitleList);
mainViewPager.setAdapter(pagerAdapter);
topTabLayout.setupWithViewPager(mainViewPager);
setUpBottomBar();
}
private void clearPagerFragments()
{
if(pagerAdapter!=null && pagerFragments!=null && pagerFragments.size()>0)
{
pagerFragments.removeAll(pagerFragments);
pagerTitleList.removeAll(pagerTitleList);
pagerAdapter.notifyDataSetChanged();
}
}
private void setUpNewsPagerFragments()
{
NewsFragment latestNewsFragment = new NewsFragment();
Bundle latestNewsBundle = new Bundle();
latestNewsBundle.putInt(NewsFragment.FIELD_CATEGORY_ID,0);
latestNewsBundle.putInt(NewsFragment.FIELD_LEAGUE_ID,0);
latestNewsBundle.putInt(NewsFragment.FIELD_COUNTRY_ID,0);
latestNewsBundle.putInt(NewsFragment.FIELD_TEAM_ID,0);
latestNewsFragment.setArguments(latestNewsBundle);
pagerTitleList.add("LATEST");
pagerFragments.add(latestNewsFragment);
PrioritizedTeamsFragment teamsFragment = new PrioritizedTeamsFragment();
pagerTitleList.add("TEAMS");
pagerFragments.add(teamsFragment);
NewsFragment articlesFragment = new NewsFragment();
Bundle articlesBundle = new Bundle();
articlesBundle.putInt(NewsFragment.FIELD_CATEGORY_ID, 0);
articlesBundle.putInt(NewsFragment.FIELD_LEAGUE_ID, 0);
articlesBundle.putInt(NewsFragment.FIELD_COUNTRY_ID, 0);
articlesBundle.putInt(NewsFragment.FIELD_TEAM_ID, 0);
articlesFragment.setArguments(articlesBundle);
pagerTitleList.add("ARTICLES");
pagerFragments.add(articlesFragment);
TopFragment topFragment = new TopFragment();
pagerTitleList.add("TOP 10");
pagerFragments.add(topFragment);
}
private void setUpMatchesPagerFragments()
{
MatchesFragment matchesFragment = new MatchesFragment();
pagerTitleList.add("MATCHES");
pagerFragments.add(matchesFragment);
StatisticsFragment statisticsFragment = new StatisticsFragment();
pagerTitleList.add("STATISTICS");
pagerFragments.add(statisticsFragment);
}
private void setUpBottomBar()
{
bottomBar.setOnTabSelectListener(new OnTabSelectListener() {
#Override
public void onTabSelected(int tabId) {
switch (tabId){
case R.id.bottom_tab_news:
clearPagerFragments();
setUpNewsPagerFragments();
pagerAdapter.notifyDataSetChanged();
break;
case R.id.bottom_tab_matches:
clearPagerFragments();
setUpMatchesPagerFragments();
pagerAdapter.notifyDataSetChanged();
topTabLayout.getTabAt(0).select();
break;
case R.id.bottom_tab_meme:
Toast.makeText(getBaseContext(),"MEME",Toast.LENGTH_SHORT).show();
break;
case R.id.bottom_tab_settings:
Toast.makeText(getBaseContext(),"Settings",Toast.LENGTH_SHORT).show();
break;
}
}
});
}
}
I showed the whole activity because code the whole activity dealing with that problem. Besides, the whole activity only contains code for creating tabs, view pager and bottom bar. All are connected.
This is my view pager adapter:
public class MainPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragmentList;
private ArrayList<String> titleList;
public MainPagerAdapter(FragmentManager fragmentManager,ArrayList<Fragment> fragmentsParam,ArrayList<String> titlesParam)
{
super(fragmentManager);
this.fragmentList = fragmentsParam;
this.titleList = titlesParam;
}
#Override
public int getCount() {
return fragmentList.size();
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
return titleList.get(position);
}
}
Why is the content or fragments of view pager are not changed when tabs are changed? What is wrong with my code?
As you can see on bottom item selected listener I tried to set the selected fragment like this:
topTabLayout.getTabAt(0).select();
I tried this as well:
mainViewPager.setCurrentItem(0);
Both are not working.
try to add a method to swap the fragment-list and call notifyDataSetChanged() in your adapter like this:
public void notifyDataSetChanged(List<Fragment> list) {
fragmentList.removeAll();
fragmentList.addAll(list);
notifyDataSetChanged();
}
changing data in activity and call adapter.notifyDataSetChanged() may fail to update your view.You can log in getItem() to check if the adapter knows the data set has changed.
Just Check which layout you are inflating in MatchesFragment class.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.matches_fragment, container, false);
}
If your tab is set correctly, under the code where the tab is set, run this again:
mainViewPager.setAdapter(pagerAdapter);
Here is my code:
selectedTab = 0;
tabLayout.getTabAt(selectedTab).select();
viewPager.setAdapter(tabsAdapter);

In tab view I want to refresh Fragment every change

viewPager = (ViewPager) findViewById(R.id.tabanim_viewpager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabanim_tabs);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
public void setupViewPager(ViewPager upViewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new ViewTodayFragment(),"Daily");
adapter.addFrag(new ViewWeekFragment(),"Weekly");
adapter.addFrag(new ViewMonthFragment(),"Monthly");
adapter.addFrag(new ViewYearFragment(),"Yearly");
viewPager.setAdapter(adapter);
}
I want to refresh fragment every time when tab changing.
inside fragment this is my code
public class ViewTodayFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
RecyclerView recyclerView;
RecyclerView.LayoutManager mLayoutManager;
RecyclerView.Adapter mAdapter;
// TODO: Rename and change types of parameters
View v;
ListView listview;
private ArrayList<DailyModel> mItems;
public static String datesel="a";
public ViewTodayFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
v=inflater.inflate(R.layout.fragment_view_today, container, false);
recyclerView =(RecyclerView)v.findViewById(R.id.view_today_lv_today);
recyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
loadData();
return v;
}
#Override
public void onResume() {
super.onResume();
loadData();
}
public void loadData(){
mItems=new ArrayList<DailyModel>();
List<Income> ll = null;
Log.d("ALLL",datesel);
if(datesel.equals("a")){
Calendar cw = Calendar.getInstance();
SimpleDateFormat format1 = new SimpleDateFormat("dd-MM-yyyy");
String currentDay=format1.format(cw.getTime());
ll=new IncomeHandler(getActivity()).getIncomeByThisDay(currentDay);
}else{
ll=new IncomeHandler(getActivity()).getIncomeByThisDay(datesel);
}
for (int i = 0; i < ll.size(); i++) {
DailyModel a=new DailyModel();
a.setCategory(ll.get(i).getWay());
a.setDescription(ll.get(i).getDes());
a.setType(ll.get(i).getType());
a.setBank("Bank");
a.setAmount(ll.get(i).getAmount());
mItems.add(a);
}
mAdapter = new DailyAdapter(mItems);
recyclerView.setAdapter(mAdapter);
}
}
So like this there are 4 tabs so i want to refresh every time it change the tab.I try to do that inside OnResume().But it also not working.
Create your pager adapter like this.
class PagerAdapter extends FragmentPagerAdapter {
private final List<String> fragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
public void addFragmentTitle(String title) {
fragmentTitleList.add(title);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new ViewTodayFragment();
} else if (position == 1) {
return new ViewWeekFragment();
} else if(position == 2){
return new ViewMonthFragment();
} else{
return new ViewYearFragment();
}
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Now you need to add fragment like this
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
adapter .addFragmentTitle("Daily");
//..... add rest of the fragment title.
viewPager.setAdapter(pagerAdapter );
hope this will help you. though i didn't try this. just writing please let me know if you get any error.
I solved this type issue currently.Please reffer my Code line by line.it might be Help you.
Thanks.
ViewPager viewPager;
ViewPagerAdapter adapter;
viewPager = (ViewPager) findViewById(R.id.tabanim_viewpager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabanim_tabs);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabanim_tabs);
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
adapter.getItem(position).onResume();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
public void setupViewPager(ViewPager upViewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new ViewTodayFragment(),"Daily");
adapter.addFrag(new ViewWeekFragment(),"Weekly");
adapter.addFrag(new ViewMonthFragment(),"Monthly");
adapter.addFrag(new ViewYearFragment(),"Yearly");
viewPager.setAdapter(adapter);
}
Implement ViewPager.OnPageChangeListener http://developer.android.com/reference/android/support/v4/view/ViewPager.OnPageChangeListener.html
I solved a similar problem. My four tabs (a sports timer with athletes - skiers or cyclsits - starting at intervals) also needed to communicate with each other. For example once a race is started, the set up controls must be disabled.
My project was based on Google's SlidingTabsColors sample.
I created a simple, one method interface called Refreshable and each of my tabs (Fragments) implemented its refresh method.
In my SlidingTabsFragment (extends Fragment) I override instantiateItem so I can capture a reference to each tab's fragment.
// Here we can safely save a reference to the created
// Fragment, no matter where it came from (either getItem() or
// FragmentManger).
//
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
/**
* Save Fragment references in an array with the MainActivity
* so that other tabs can be refreshed (state updated) depending on
* changes to other tabs.
*/
MainActivity a = (MainActivity)getActivity();
a.addFragment((Refreshable)createdFragment);
return createdFragment;
}
My main is an observer of my data model, but yours may different.
This is the main's method to "register" the fragments.
/**
* Accepts the specified fragment and adds to the list of "Refreshable" Fragments.
* If it is already registered, it is not added a second time.
*
* #param fragment
* the Fragment (Observer) to add.
*/
public void addFragment(Refreshable fragment) {
if (fragment == null) {
throw new NullPointerException("fragment == null");
}
synchronized (this) {
if (!mRefreshables.contains(fragment))
mRefreshables.add(fragment);
}
}
In my case, this code is in the update method of my Observer. My data has changed (race started, interval countdown expired, finisher recorded) and I can refresh all tabs. I cannot call from one tab to another because of race (no pun intended) conditions.
/**
* Call refresh on every Fragment to update state.
*/
for (Refreshable refreshable : array) {
refreshable.refresh();
}
Each tab's refresh method does its own thing.
You may not need an Observer co-ordinating all tabs, but at least you'll have a reference to them and a method other than onResume (which didn't work for me either) to call and have the content refresh itself.
your answer....you must use
viewPager.setAdapter(adapter);
when your selected tab is change.

Updating fragments from Activity in a ViewPager

I'm new to Android developing and I would really appreciate some help here.
I'm using a fragment that contains a TextView and I'm using 5 instances of the same MyFragment class.
In the activity, i got a button and a ViewPager, and I need the button to update all the fragment instances content, whenever its clicked.
Here's the Activity
public class MainActivity extends FragmentActivity {
final static String[] CONTENT = {"a", "b"};
ViewPager pager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<MyFragment> fragments = new Vector<MyFragment>();
for(int i = 0; i < 5; i++){
MyFragment fragment = new MyFragment(CONTENT);
fragments.add(fragment);
}
PagerAdapter adapter = new PagerAdapter(this.getSupportFragmentManager(), fragments);
pager = (ViewPager) findViewById(R.id.viewpager);
pager.setAdapter(adapter);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//method that isn't working
PagerAdapter adapter = (PagerAdapter)pager.getAdapter();
for(int i = 0; i < 5; i++){
MyFragment fragment = (MyFragment) adapter.getItem(i);
fragment.textView.setText(fragment.content[1]);
}
}
});
}
}
The Fragment
public class MyFragment extends Fragment{
String[] content;
TextView textView;
public MyFragment(String[] content) {
this.content = content;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_content, container, false);
textView = (TextView) view.findViewById(R.id.textView1);
textView.setText(content[0]);
return view;
}
}
And the FragmentPagerAdapter
public class PagerAdapter extends FragmentPagerAdapter{
List<MyFragment> fragments;
public PagerAdapter(FragmentManager fm, List<MyFragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int arg0) {
return fragments.get(arg0);
}
#Override
public int getCount() {
return fragments.size();
}
}
The OnClick method gives me a NullPointerException whenever i try to access a fragment from the adapter which is less than adapter.getCurrentItem() - 1, or more than adapter.getCurrentItem() + 1.
Any idea on how to update all the fragments at the same time?
Thanks in advance.
The easiest way to update those fragments is to use your code and set the number of fragments that the ViewPager holds in memory to the number of total fragments - 1(so all fragments are valid no matter at what page you are). In your case:
pager.setOffscreenPageLimit(4); // you have 5 elements
You can still use the method from my comment with the method onPageScrollStateChanged(so the update will start the moment the user starts swiping) to see when the user is starting to swipe the pager and update the fragments to the left and right of the currently visible fragment, but this will be a bit difficult to get right so I recommend to go with the first option.
Some points regarding your code containing fragments:
If you nest the fragment class make it static so you don't tie it to the activity object.
Don't create a constructor for a Fragment besides the default one. If the framework needs to recreate the fragment it will call the default constructor and if it is not available it will throw an exception. For example, try to change the orientation of the phone/emulator and see what happens(this is one of the cases when Android will recreate the fragments). Last, use a custom name for the ViewPager's adapter, you use PagerAdapter which is the name of the super class of FragmentViewPager and it's very confusing for someone reading your code.
If you need to pass data to the Fragment you could use a creation method like the one below:
public static MyFragment newInstance(String text) {
MyFragment f = new MyFragment();
Bundle b = new Bundle();
b.putString("content", text);
f.setArguments(b);
return f;
}
The text will be available in MyFragment by using getArguments().getString("content");

Categories

Resources