PagerSlidingStrip is also loading another fragment - android

I have implemented Pager Sliding Strip and it is working totally fine.
I have 5 tabs each containing different fragment. When I click on 2nd tab to load respective fragment, it also load details of 3rd fragment, it showing the toast I coded in 3rd tab's fragment.
this is totally ruined the apps performance, How come I solve this problem I don't have any idea whats actually going on.
I am working on a really big project I cannot post the whole code.
Please Help me with this, I will post the respective code on demand.
Regards.
EDIT
Notification Fragment which is loading another fragment
ListView notification_listview;
ArrayList<FragmentNotificationDTO> arraylist;
NotificationAdapter adapter;
private static View notificationView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (notificationView != null) {
ViewGroup parent = (ViewGroup) notificationView.getParent();
if (parent != null)
parent.removeView(notificationView);
}
notificationView = inflater.inflate(R.layout.fragment_notification,
container, false);
initLayout(notificationView);
loadData();
return notificationView;
}
private void initLayout(View view) {
notification_listview = (ListView) view.findViewById(R.id.notification_listview);
arraylist = new ArrayList<FragmentNotificationDTO>();
adapter = new NotificationAdapter(mContext, arraylist);
notification_listview.setAdapter(adapter);
}
This is Food Fragment which is loaded also when we click on Notification Tab
private static View foodlistView;
RelativeLayout rl_foodshare, rl_foodrequested, rl_foodkitchen;
TextView tv_foodshare, tv_foodrequested, tv_foodkitchen;
ImageView img_foodshare, img_foodrequested, img_foodkitchen;
Fragment fr;
FragmentManager fm;
FragmentTransaction fragmentTransaction;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (foodlistView != null) {
ViewGroup parent = (ViewGroup) foodlistView.getParent();
if (parent != null)
parent.removeView(foodlistView);
}
foodlistView = inflater.inflate(R.layout.fragment_location_list,
container, false);
initLayout(foodlistView);
ChangeFragment(1);
return foodlistView;
}
MainActivity.java which contains the PagerSlidingStrip & View Pager
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()));
PagerSlidingTabStrip PGSTRIP = (PagerSlidingTabStrip) findViewById(R.id.tabs);
PGSTRIP.setViewPager(viewPager);
viewPager.setOffscreenPageLimit(0);
}

I solved my problem by overriding this method in each of my fragment and then calling the loading method when fragment's visibility is true to user.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// load data here
}else{
// fragment is no longer visible
}
}

Related

Blank Fragment inside Tablayout / Viewpager

So i'm desperately looking for an answer to my problem. I spend hours try and retry some things but that did not work.
So here is my problem :
I have only one activity for my application which is the main activity.
This activity contains a bottom navigation bar and a frame layout to load a fragment depending the choice of the item on the bottom navigation bar.
My PredictionsFragment (loaded by bottom navigation bar) contains a TabLayout (using SmartTabLayout library). In this Fragment, a list of data is loaded in a thread because it use internet connection. TabLayout is containing PredictionsViewFragment which displays a RecyclerView.
When I select the PredictionsFragment on my bottom navigation bar, tablayout and all the recyclerview are perfectly displayed.
But when I go to another item and go back to PredictionsFragment it displays a blank view...
PredictionsFragment code :
public class PredictionsFragment extends Fragment {
private static List<Country> countryList = new ArrayList<>();
private ViewPager viewPager;
private SmartTabLayout viewPagerTab;
private FragmentStatePagerItemAdapter adapter;
private FragmentPagerItems pages;
private ProgressBar progressBar;
private ViewGroup tab;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_predictions_tab, container, false);
initView(view);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (countryList.size() == 0) {
refresh();
} else {
refreshViewPager();
}
}
private void initView(View view) {
tab = (ViewGroup) view.findViewById(R.id.tab);
tab.addView(LayoutInflater.from(getContext()).inflate(R.layout.fragment_view_predictions, tab, false));
progressBar = (ProgressBar) view.findViewById(R.id.progressbar);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPagerTab = (SmartTabLayout) view.findViewById(R.id.viewpagertab);
viewPager.setOffscreenPageLimit(countryList.size());
pages = new FragmentPagerItems(getContext());
adapter = new FragmentStatePagerItemAdapter(getFragmentManager(), pages){
public int getItemPosition(Object object) {
return POSITION_NONE;
}
};
viewPager.setAdapter(adapter);
viewPagerTab.setViewPager(viewPager);
}
private void refresh() {
// Thread car connexion internet
new Thread(new Runnable() {
#Override
public void run() {
countryList = InternetData.getCountryList();
refreshViewPager();
}
}).start();
}
private void refreshViewPager() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
for (Country country : countryList) {
pages.add(FragmentPagerItem.of(country.getCode(), PredictionsViewFragment.class));
}
adapter.notifyDataSetChanged();
viewPagerTab.setViewPager(viewPager);
progressBar.setVisibility(View.GONE);
}
});
}
public static List<Prediction> getPredictionList(int index) {
return countryList.get(index).getPredictionList();
}
}
PredictionsViewFragment code :
public class PredictionsViewFragment extends Fragment {
private RecyclerView recyclerView;
private PredictionAdapter adapter;
private int position;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recycler_view_pronos, container, false);
position = FragmentPagerItem.getPosition(getArguments());
initRecyclerView(view);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
private void initRecyclerView(View view) {
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
adapter = new PredictionAdapter(PredictionsFragment.getPredictionList(position));
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
}
}
Screenshot of the blank fragment and the app
EDIT :
When I use getChildFragmentManager() method :
adapter = new FragmentStatePagerItemAdapter(getChildFragmentManager(), pages){
public int getItemPosition(Object object) {
return POSITION_NONE;
}
};
I get this error when I go the second time on the Fragment (The first time I go on it, it works perfectly) :
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.util.SparseArray.get(int)' on a null object reference
at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:936)
at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:217)
at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1461)
at android.view.View.dispatchRestoreInstanceState(View.java:18608)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3821)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3827)
at android.view.View.restoreHierarchyState(View.java:18586)
at android.support.v4.app.Fragment.restoreViewState(Fragment.java:494)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1486)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1784)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1852)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:802)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2625)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2411)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2366)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2273)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:733)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
EDIT 2 :
I added these lines to the onViewCreated method on my PredictionsFragment :
else {
refreshViewPager();
}
But it does absolutely nothing... The name of the tab appears properly but not the recyclerview...
It's like the Fragment inside the tablayout isn't loaded
EDIT 3 :
I have added a SwipeRefreshLayout to my recyclerview and for the 2 first tabs i can't do a pull to refresh and from the 3rd tabs only one item of the recyclerview appears and pull to refresh "works" but it displays only one item in the recyclerview
If you have any questions tell me I'll do my best to answer it !
Thanks in advance for you help I appreciate it
Use setOffsetScreenPageLimit in viewPager: This will help you to store the data in the pagers fragments when you navigate through bottom tabs.
viewPager.setOffscreenPageLimit(the number of tab you are setting);
For refreshing the data in recycler view you can use "Swipe refresh"
So I solved my problem...
You have to use this :
adapter = new FragmentPagerItemAdapter(getChildFragmentManager(), pages);
Use FragmentPagerItemAdapter and NOT FragmentStatePagerItemAdapter
And for sur you have to use getChildFragmentManager()
I was also using BottomNavigationView to open tabLayout with viewPager & faced the same problem. FragmentStatePagerAdapter can be used for this.
This class handles saving and restoring of fragment's state -> It's in the documentation

ListView in Fragment not refreshed

I created a tabbed app where the main acitvity contains two layouts. The top layout contains the actual tabbar (which is a fragment). Underneth the content layout contains another fragments depending on which tabbar button the user has clicked. In order to stay compatible with older android versions I use android.support.v4.app.Fragment.
So, in the tabbar menu I added two buttons and each button triggers another fragment in the content. This is what the code looks like:
public class TabbarMenuFragment extends Fragment implements View.OnClickListener {
LiveFragment liveFragment;
OddsFragment oddsFragment;
FragmentTransaction fragmentTransaction;
Button liveButton;
Button oddsButton;
public TabbarMenuFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
liveFragment = new LiveFragment();
oddsFragment = new OddsFragment();
fragmentTransaction = getFragmentManager().beginTransaction().add(R.id.content_view, oddsFragment);
fragmentTransaction.commit();
View rootView = (View) inflater.inflate(R.layout.tabbar_menu, container, false);
liveButton = (Button) rootView.findViewById(R.id.liveButton);
liveButton.setOnClickListener(this);
oddsButton = (Button) rootView.findViewById(R.id.oddsButton);
oddsButton.setOnClickListener(this);
return rootView;
}
public void updateUIInTabs() {
liveFragment.updateUI();
}
#Override
public void onClick(View v) {
if(v == liveButton) {
fragmentTransaction = getFragmentManager().beginTransaction().replace(R.id.content_view, liveFragment);
fragmentTransaction.commit();
}
if(v == oddsButton) {
fragmentTransaction = getFragmentManager().beginTransaction().replace(R.id.content_view, oddsFragment);
fragmentTransaction.commit();
}
updateUIInTabs();
}
}
The important thing is that the liveFragment is a Fragment that contains a ListView:
public class LiveFragment extends Fragment {
LiveMainAdapter adapter;
ListView list;
LayoutInflater inflater;
View rootView;
public LiveFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
this.inflater = inflater;
rootView = (View) inflater.inflate(R.layout.live_fragment, container, false);
adapter = new LiveMainAdapter(inflater);
list = (ListView) rootView.findViewById(R.id.live_fragment_ListView);
list.setAdapter(adapter);
list.setDivider(null);
list.setDividerHeight(0);
return rootView;
}
public void updateUI() {
if(list != null) {
list.invalidate();
adapter.createRowObjects();
adapter.notifyDataSetChanged();
}
}
}
The oddsFragment is so far just a dummy with a TextView:
public class OddsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = (View) inflater.inflate(R.layout.odds_fragment, container, false);
return rootView;
}
}
Now there are two settings which are important:
First:
As described above: I start the app and the oddsFragment is initally shown. Now, when I click on the liveFragment button the liveFragment's ListView is not updated.
Clicking again on the button for oddsFragment the oddsFragment is properly shown. Clicking back to liveFragment I get nothing - no ListView is shown.
The second setting:
Is exactly the same as the first, but instead I set the liveFragment as the intial view that is in TabbarMenuFragment I replace:
fragmentTransaction = getFragmentManager().beginTransaction().add(R.id.content_view, oddsFragment);
with
fragmentTransaction = getFragmentManager().beginTransaction().add(R.id.content_view, liveFragment);
Then the ListView is properly shown and the data in the list view is updated and displayed correctly. However, if I click on oddsFragement and then again on liveFragement the ListView has disappeared.
I already tried different things for over two hours now and I'm pretty desperated because I have not clue what might be the reason for this wired behaviour.
Anybody got an idea what is going on here?
Give this a try...
In your LiveFragment add a Handler and a Runnable and update the UI from your Runnable.
Handler handler = new Handler();
Runnable updater = new Runnable()
{
public void run()
{
if(list != null) {
list.invalidate();
adapter.createRowObjects();
adapter.notifyDataSetChanged();
}
}
};
and then change your updateUI() method in LiveFragment
public void updateUI()
{
handler.post(updater);
}

Android: Unable to display a fragment inside a viewpager where viewpager was inside a fragment

Having problem showing Fragment inside a ViewPager.
I have a ViewPager which was hosted inside Fragment where this Fragment was inside the Activity.
This ViewPager has a pagerTabStrip. Each page in ViewPager are Fragment of special usage.
This is how I setup the viewpager with PagerAdapter
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pager_screen,
container, false);
ViewPager pager = (ViewPager) rootView.findViewById(R.id.vp_main);
pager.setAdapter(new MainTabAdapter(rootView.getContext(),getFragmentManager()));
return rootView;
}
This is fine, I can see the pager. Within the MainTabAdapter I have a getItem which I select differnt fragments.
#Override
public Fragment getItem(int arg0) {
// TODO Auto-generated method stub
Log.w("ALBUM", types[arg0].toString());
Fragment fragment = FragmentType.getFragment(types[arg0]);
return fragment;
}
This is fine too. I can get the right fragment. When showing the Fragment of different page, none of them showing. Below is my code on one of the Fragment to inflating an xml
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_local_screen,
container, false);
Bundle data = new Bundle();
data.putStringArray("PROJECTION", new String [] {
MediaStore.Video.VideoColumns._ID,
MediaStore.Video.VideoColumns.BUCKET_DISPLAY_NAME,
MediaStore.Video.VideoColumns.BUCKET_ID,
MediaStore.Video.VideoColumns.DATE_TAKEN,
MediaStore.Video.VideoColumns.DATE_ADDED,
MediaStore.Video.VideoColumns.DESCRIPTION,
MediaStore.Video.VideoColumns.DURATION});
data.putString("SELECTION", null);
data.putStringArray("SELECTIONARRAY", null);
data.putString("SORTORDER", MediaStore.Video.VideoColumns.BUCKET_DISPLAY_NAME + " LIMIT " + mLimit);
VideoCursorAdapter adapter = new VideoCursorAdapter(getActivity(),null,true);
LocalVideos videos = new LocalVideos(getActivity(), adapter);
getLoaderManager().initLoader(LocalVideos.LoaderID.THUMBNAIL.getID(), data, videos);
ListView listView = (ListView)rootView.findViewById(R.id.listVideos);
//listView.setAdapter(adapter);
videos.setView(listView);
return rootView;
This works, if I remove the viewpager. When I put the ViewPager code, this fragment doesn't show up.

Why does the fragment's onCreateView, onCreate, onActivityCreated are called

I have an app, that deals with fragments and ViewPager. I have three fragments in a ViewPager. When you switch between them, it always causes the other two fragments to call their's onCreateView methods. How to do it only once, only when FragmentActivity is created???
I've read some questions and tried the solutions, but the fragments still have the same behavior.
ListFragment onCreate called twice
onCreate() and onCreateView() invokes a lot more than required (Fragments)
Here is some code, if it helps you, guys:
MainActivity:
public class StartingActivity extends FragmentActivity implements View.OnClickListener {
ViewPager viewPager;
CirclePageIndicator pageIndicator;
Button discount;
Button qrCode;
Button pay;
TabHost tabHost;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.starting_layout);
viewPager = (ViewPager) findViewById(R.id.pager);
if (savedInstanceState == null) {
Fragment firstPage = Fragment.instantiate(this, FindTovarFragment.class.getName());
Fragment secondPage = Fragment.instantiate(this, MainWindowActivity.class.getName());
Fragment thirdPage = Fragment.instantiate(this, MapActivity.class.getName());
if ((firstPage != null && !firstPage.isDetached())|| (secondPage != null && !secondPage.isDetached()) || (thirdPage != null && !thirdPage.isDetached())) {
List<Fragment> viewPagerFragments = new ArrayList<Fragment>();
viewPagerFragments.add(firstPage);
viewPagerFragments.add(secondPage);
viewPagerFragments.add(thirdPage);
PageAdapter pageAdapter = new PageAdapter(getSupportFragmentManager(), viewPagerFragments);
viewPager.setAdapter(pageAdapter);
pageIndicator = (CirclePageIndicator) findViewById(R.id.circle);
pageIndicator.setViewPager(viewPager);
pageIndicator.setCurrentItem(pageAdapter.getCount() - 2);
}
}
}
MapActivity:
public class MapActivity extends Fragment implements OnMyLocationListener {
//Тэг для логов
private static final String TAG = "MapActivity";
List<Address> addressList;
private static final String STRING_LOCATION = "";
ArrayList<TorgCentr> randomTorgCentr;
ArrayList<String> torgCentrNames;
Context context;
AutoCompleteTextView searchTorgCentr;
OverlayManager overlayManager;
MapController mapController;
TextView textView;
double longitude;
double latitude;
double itemLongitude;
double itemLatitude;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "MapActivity onCreateView");
View view = (LinearLayout) inflater.inflate(R.layout.map_layout, container, false);
final MapView mapView = (MapView) view.findViewById(R.id.map);
textView = (TextView) view.findViewById(R.id.searchlocation);
searchTorgCentr = (AutoCompleteTextView) view.findViewById(R.id.autoCompleteTextView);
mapView.showBuiltInScreenButtons(true);
mapController = mapView.getMapController();
context = getActivity();
return view;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "MapActivity onCreate");
}
public void onActivityCreated(Bundle savedInstanceState) {
Log.d(TAG, "MapActivity onActivityCreated");
context = getActivity();
SetRightMapDisplayAddress rightMapDisplayAddress = new SetRightMapDisplayAddress();
rightMapDisplayAddress.execute(STRING_LOCATION);
DownloadSuperMarketsArray superMarketsArray = new DownloadSuperMarketsArray();
superMarketsArray.execute();
overlayManager = mapController.getOverlayManager();
overlayManager.getMyLocation().setEnabled(false);
super.onActivityCreated(savedInstanceState);
}
Second Fragment:
public class MainWindowActivity extends Fragment {
private static final String TAG = "MainWindowActivity";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "MainWindowActivity onCreateView");
View view = (RelativeLayout) inflater.inflate(R.layout.main_window_layout, container, false);
if (container == null) {
return null;
}
return view;
}
}
And the third one:
public class FindTovarFragment extends Fragment {
private static final String TAG= "FindTovarFragment";
Context context;
ArrayList<Category> categories;
Spinner categoryContainer;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "FindTovarFragment onCreateView");
View view = (LinearLayout) inflater.inflate(R.layout.find_tovar_main_layout, container, false);
categoryContainer = (Spinner) view.findViewById(R.id.category);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG, "FindTovarFragment onActivityCreated");
DownloadCategory downloadCategory = new DownloadCategory();
downloadCategory.execute();
}
Logs for MapActivity:
06-20 11:06:37.709: DEBUG/MapActivity(1290): MapActivity onCreate
06-20 11:06:37.709: DEBUG/MapActivity(1290): MapActivity onCreateView
06-20 11:06:38.509: DEBUG/MapActivity(1290): MapActivity onActivityCreated
Then again and again:
06-20 11:07:53.239: DEBUG/MapActivity(1290): MapActivity onCreate
06-20 11:07:53.239: DEBUG/MapActivity(1290): MapActivity onCreateView
06-20 11:07:53.429: DEBUG/MapActivity(1290): MapActivity onActivityCreated
06-20 11:08:23.029: DEBUG/MapActivity(1290): MapActivity onCreate
06-20 11:08:23.039: DEBUG/MapActivity(1290): MapActivity onCreateView
06-20 11:08:23.269: DEBUG/MapActivity(1290): MapActivity onActivityCreated
Thank you very much in advance.
ViewPager retain in memory 1 page by default, to either side of the current page. So it would not re-create those pages when swiping 1 page left/right of the current page. But when swipe more than 1 pages to left/right, it would re-create those page again, hence called OnCreateView(), OnCreate().
If app uses few pages 3, you can increase the number of pages to retain by calling,
mViewPager.setOffscreenPageLimit(2);
Described here
I would change your architecture for this one on the android developer documentation:
http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html
but I would change some things...
1-I would change this method:
/**
* The Fragment's UI is just a simple text view showing its
* instance number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager_list, container, false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText("Fragment #" + mNum);
return v;
}
For something like this where we decide which fragment you populate depending the position of the viewPager:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
SupportFragmentManager ft = getChildFragmentManager().beginTransaction();
String tag = "";
Fragment fragment = null;
switch (mNum) {
case 0:
fragment = new MyFragmentZero();
tag = FragmentTags.TAG_0;
break;
case 1:
fragment = new MyFragmentOne();
tag = FragmentTags.TAG_3;
break;
case 2:
fragment = new MyFragmentTwo();
tag = FragmentTags.TAG_2;
break;
default:
break;
}
/*OPTIONAL We can pass arguments to the fragments
Bundle args = new Bundle();
args.putInt(Arguments.ARG_POSITION, mNum);
fragment.setArguments(args);*/
//Place the fragment in the container
ft.replace(R.id.fragment_container fragment, tag);
ft.commit();
//You need a base layout for all fragment and use nested fragments later or you can define the layout for each position(mNum) inside the switch.
return inflater.inflate(R.layout.fragment_layout_default_for_all_views, container,
false);
}
Like this you will have a good architecture and once it is working like this should be fine.
Anyway you must know how the viewPager works populating the fragment in the different positions.
When you start on the position 0, then the fragment on the position 0 and the one of the position 1 are created.
Then when you swipe to the position 1 the fragment on the 2 position is created, so you have now the three fragments created on the different positions (0,1,2..assuming you have only 3 pages on the viewPager).
We swipe to the position 2, the last one, and the fragment on the first position (0) get destroy, so we have now the fragments on the positions 2 and 3.
I hope it helped and let me know if you have any problem. Cheers
Finally I was able to figure it out. Just need to override the destroyItem method so that it won't destroy objects. Hope this is going to be useful for someone.
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
Log.d(TAG, "destroy!");
}

Why doesn't my viewpager work in a Fragment?

I have the following code for my fragment. I pretty much took this from a basic view pager example and slapped it into a fragment to test for a project I'm working on.
I'm using ACtionBarSherlock, and viewPagerIndicator libraries. The Fragment below contains a viewPager that in this example is supposed to swipe between simple title strings.
I tried the example with the ViewPager and ViewPagerIndicator in an activity, and no problem. But the second I put it into a fragment. BOOM, nothing but a black screen... NO errors, just a black screen...I feel like I must be inflating, or accessing the layout incorrectly or something...
Any ideas?
Here's the code:
public class TestFragment extends SherlockFragment {
//~Constants----------------------------------------------
//~Data Fields--------------------------------------------
//~Constructors--------------------------------------------
#Override
public void onCreate(Bundle savedInstanceState) {
//Setup view
super.onCreate(savedInstanceState);
View view = onCreateView(getLayoutInflater(savedInstanceState), null, savedInstanceState);
ViewPagerAdapter adapter = new ViewPagerAdapter( this.getSherlockActivity() );
ViewPager pager =
(ViewPager)view.findViewById(R.id.free_time_day_pager);
TitlePageIndicator indicator =
(TitlePageIndicator)view.findViewById(R.id.titles);
pager.setAdapter( adapter );
indicator.setViewPager( pager );
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.free_time_fragment_layout, null, false);
return view;
}
//~Methods-------------------------------------------------
}
Dont call onCreateView that is wrong.
onCreateView is an overridden method which is called by the FragmentManger to handle the Fragment lifecycle.
private ViewPager mViewPager;
private TitlePagerIndicator mIndicator;
// Called first
#Override
public void onCreate(Bundle savedInstanceState) {
//Setup view
super.onCreate(savedInstanceState);
}
// Called second
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.free_time_fragment_layout, null, false);
return view;
}
// Called third
#Override
public View onViewCreated(View v){
super.onViewCreated(v);
mViewPager = (ViewPager) v.findViewById(R.id.free_time_day_pager);
mIndicator = (TitlePageIndicator)v.findViewById(R.id.titles);
}
public void onActivityCreated(Bundle bdl){
super.onActivityCreated(bdl);
ViewPagerAdapter adapter = new ViewPagerAdapter( getSherlockActivity() );
mViewPager.setAdapter(adapter);
mIndicator.setViewPager(pager);
}
Also be aware if you are using a FragmentPagerAdapter you require a special method to create the ViewPagerFragment, its a bit tricky but refer to this gist.
Read about Fragment Lifecycles here too.
Cheers
Use this.
compile 'com.android.support:appcompat-v7:23.0.1'
work for me.

Categories

Resources