i am developing an app which has a few fragments and i have set them up using an adapter which extends fragmentpager adapter, and i want the fragments to repeat when any of the end is reached. for e.g if i have set up 4 fragments and then when the user reaches the 4th fragment ,instead of blocking the view,the view should shift to the first fragment ...
i have been able to set up the fragments but don't know how to achieve this loop thing...
here is the code for the adapter
package sourcecode.jazzplayer;
import java.util.List;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
public class ViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
private static String[] titles = new String[] {"Songs", "My Playlists", "Artists","Albums"};
public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
#Override
public String getPageTitle( int position )
{
return titles[ position ];
}
}
and here is the code how i have set up the fragments
package sourcecode.jazzplayer;
import java.util.List;
import java.util.Vector;
import sourcecode.jazzplayer.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class MyMusic extends FragmentActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mymusic);
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, FragmentSongs.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentArtists.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentPlaylists.class.getName()));
fragments.add(Fragment.instantiate(this, FragmentAlbums.class.getName()));
ViewPagerAdapter adapter = new ViewPagerAdapter(super.getSupportFragmentManager(), fragments);
ViewPager pager = (ViewPager)super.findViewById(R.id.viewpager);
pager.setAdapter(adapter);
pager.setOffscreenPageLimit(4);
pager.setCurrentItem(0);
}
}
Check the Infinite Viewpager project on Github.
It is very simple with a FragmentPagerAdapter:
#Override
public Fragment getItem(int position) {
return this.fragments.get(position % 4);
}
#Override
public long getItemId(int position) {
return position % 4;
}
#Override
public int getCount() {
return Integer.MAX_VALUE;
}
And when initializing the ViewPager set the initial page to a very high value, so you can move the pages both ways. For 4 pages, 0x40000000 is roughly half of Integer.MAX_VALUE and is divisible by 4 (id is 0).
I just pushed my recent code to GitHub LoopingViewPager, I hope this will help you.
This ViewPager can work with views and with fragments, only small code modifications are needed in your adapter and xml files.
Related
Im using FragmentPagerAdapter and ViewPager to show two fragments. First time when open the fragment, both show/work fine. When I go to another activity or go to another fragment outside these 2 and come back, nothing shows up. Here's the code.
Event:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Events extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.event, container, false);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) rootView.findViewById(R.id.pager);
FragmentManager fm = getFragmentManager();
viewPager.setAdapter(new MyFragmentPageAdapter(fm));
// Give the SlidingTabLayout the ViewPager
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) rootView.findViewById(R.id.tabs);
// Center the tabs in the layout
slidingTabLayout.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.ColorSecondary);
}
});
slidingTabLayout.setDistributeEvenly(true);
slidingTabLayout.setViewPager(viewPager);
return rootView;
}
}
MYFramentAdapter.class:
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyFragmentPageAdapter extends FragmentPagerAdapter{
final int PAGE_COUNT = 2;
private String tabTitles[] = new String[] { "Upcoming", "Calendar" };
private Context context;
public MyFragmentPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return FragmentEvents.newInstance(0);
case 1: return FragmentCalendar.newInstance(1);
default: return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
Resolved:
I had to user getChildFragmentManager() in ViewPager because of nested fragments.
I'm using pager view in the regular way. in the code below I get the error: android.support.v4.app.FragmentManager cannot be applied to android.app.FragmentManager. I checked all the solutions for this and implemented them as it can be seen (the import's seems OK), and still I have this error...
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
public class MyActivity extends FragmentActivity {
private static int NUM_PAGES = 0; //The number of pages to show.
private static ViewPager mPager; //The pager widget
private static PagerAdapter mPagerAdapter; //The pager adapter
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
mPager = (ViewPager) findViewById(R.id.pager);
//Next line is error
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
/**
* A simple pager adapter
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return MyFragment.create(position);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
...
}
Use getSupportFragmentManager() instead of getFragmentManager(). Accordingly to the imports of your class you are using the Fragment from the support's library
I'm trying to add/remove dynamically fragments in a ViewPager following a button click, but if I remove the fragment (a form) by clicking on back button, and add the fragment again, the form has kept its data (EditText not empty).
Here is my adapter :
package com.thomas.playlists.viewPager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
public class ViewPagerAdapter extends FragmentPagerAdapter
{
ArrayList<Fragment> mList = null;
public ViewPagerAdapter(FragmentManager fm)
{
super(fm);
mList = new ArrayList<Fragment>();
}
public void add(Fragment fragment)
{
mList.add(fragment);
}
public void removeLast()
{
if(mList.size() > 1)
mList.remove(getCount() - 1);
}
#Override
public Fragment getItem(int i)
{
return mList.get(i);
}
#Override
public int getCount()
{
return mList.size();
}
}
Adding proccess used twice (in main Activity) :
PlaylistFragment playlistFragment = new PlaylistFragment();
mViewPagerAdapter.add(playlistFragment);
mViewPagerAdapter.notifyDataSetChanged();
mViewPager.setCurrentItem(mViewPagerAdapter.getCount() - 1, true);
Removing a page (still in main Activity) :
mViewPagerAdapter.removeLast();
mViewPagerAdapter.notifyDataSetChanged();
mViewPager.setCurrentItem(mViewPagerAdapter.getCount() - 1, true);
How can I remove the fragment properly ?
EDIT : I tried this but the form isn't reseted;
EDIT 2 : After instanciating the second fragment, its onCreate() method isn't called.
Extend FragmentStatePagerAdapter, and override getItemPosition methode:
public class ViewPagerAdapter extends FragmentStatePagerAdapter
{
//... your existing code
#Override
public int getItemPosition(Object object) {
int position = mList.indexOf(object);
return position == -1 ? POSITION_NONE : position;
}
}
I have followed official documentation on how to implement swipe views with TabStrip instead of Tabs in order to create a Fragment (FragmentMyAccount.class) that contains Nested Fragments (FragmentMyProfile.class and FragmentMyLibrary.class). These nested fragments correspond to the two tabs managed by a childFragmentManager.
The two tabs and astuetz's pagerSlidingTabStrip work fine, but adapter's getPageTitle method doesn't have access to String resources and can only return a hardcoded string for each tab title (see on the bottom of the code). The compile-time error that appears when I try to access the xml resources reads:
"FragmentMyAccount.this cannot be referenced from a static context"
If the code below is not possible to tweak, what alternative implementation would be adequate to achieve my goal?
package com.kouretinho.myapp;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.astuetz.PagerSlidingTabStrip;
public class FragmentMyAccount extends Fragment {
private static final int NUM_ITEMS = 2;
MyAccountAdapter mAdapter;
ViewPager mPager;
PagerSlidingTabStrip mTabStrip;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my_account, container, false);
// Initialize the FragmentPager Adapter
mAdapter = new MyAccountAdapter(getChildFragmentManager());
// Initialize the ViewPager and set an adapter
mPager = (ViewPager) rootView.findViewById(R.id.viewpager_my_account);
mPager.setAdapter(mAdapter);
// Initialize the TabStrip and bind the tabs to the ViewPager
mTabStrip = (PagerSlidingTabStrip) rootView.findViewById(R.id.viewpager_tab_strip);
mTabStrip.setViewPager(mPager);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
public static class MyAccountAdapter extends FragmentPagerAdapter{
private static final int MY_PROFILE = 0;
private static final int MY_LIBRARY = 1;
private static final String sExceptionMessage = "FragmentPagerAdapter was asked to getItem " +
"with position other than 0 or 1. This FragmentPagerAdapter can only return one of" +
"two Fragments at position 0 or 1.";
public MyAccountAdapter(FragmentManager fm){
super(fm);
}
#Override
public int getCount() {
return FragmentMyAccount.NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
switch (position){
case MY_PROFILE:
return new UserProfileFragment();
case MY_LIBRARY:
return new UserBooksFragment();
default:
throw new IllegalStateException(sExceptionMessage);
}
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case MY_PROFILE:
// ********** THIS LINE IS PROBLEMATIC, cannot get Localised String resources
return FragmentMyAccount.this.getActivity().getResources().getString(R.id.my_profile);
case MY_LIBRARY:
return "my_library";
default:
return "no_title";
}
}
}
}
In your case you have to replace:
public static class MyAccountAdapter extends FragmentPagerAdapter
with
public class MyAccountAdapter extends FragmentPagerAdapter
Another way to fix this is to pass Context to MyAccountAdapter in constructor (like you do with FragmentManager).
I am trying find a solution simular this https://stackoverflow.com/a/13925130/1634451 but the poster didn't explain what R.id.products_list_linear is. I tried to set R.id.products_list_linear as the id of my linearlayout for the fragment i am trying to replace. But that just overlays the 2 fragments on top of each other. I am pretty sure that i need to get the id of the container in the viewpager but i don't know how to get this id.
Edit:
To clarify i am trying to replace a fragment in a view pager with another my code looks almost exactly like the answer I posted but when I make R.id.products_list_linear the I'd of the fragment I am trying to replace layout. The fragment I am replacing just gets overlaid on the one I am trying to replace
Replace Fragments Within a View Pager
Try this customized ViewPager Adapter,..
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments=null;
private FragmentManager fragmentManager=null;
public ViewPagerAdapter(FragmentManager fragmentManager,List<Fragment> fragments) {
super(fragmentManager);
this.fragments=fragments;
this.fragmentManager=fragmentManager;
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object)
{
super.setPrimaryItem(container,0,object);
}
#Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
fragmentManager.executePendingTransactions();
fragmentManager.saveFragmentInstanceState(fragments.get(position));
}
public void replaceItem(int position,Fragment fragment)
{
fragments.set(position, fragment);
this.notifyDataSetChanged();
}
}
call it from activity with fragment as arguments,
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this, Fragment1.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment2.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment3.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment4.class.getName()));
fragments.add(Fragment.instantiate(this, Fragment5.class.getName()));
mPagerAdapter=new ViewPagerAdapter(getFragmentManager(), fragments);
When you replace view/fragment inside of viewPager then use,
mPagerAdapter.replaceItem(2,Fragment.instantiate(this, Fragment5.class.getName()));
I ended up going with a different approach that worked out nicely for me. I used a ViewSwitcher for the fragment in the viewpager.