Reputation: 397
is it possible for a View Pager with FragmentPagerAdapter to be its own fragment and not a fragment activity?
Here is a picture of what I mean.
http://d3a0c3fa3t59bz.cloudfront.net/wordpress/wp-content/uploads/2013/01/timetable1.png
Notice on the left most side its a view pager with Thursday and Friday. This is the kind of arrangement I am looking for a fragment view pager as a fragment itself.
If someone could post an example, advice or provide a link to carry this out, I would be most grateful. Thank you in advance.
Upvotes: 1
Views: 76
Reputation: 1007534
Yes, though you have to use nested fragments, which have given many developers headaches.
This sample project demonstrates how it works. Here is the PagerFragment
from that sample that hosts the ViewPager
:
/***
Copyright (c) 2012 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
From _The Busy Coder's Guide to Android Development_
http://commonsware.com/Android
*/
package com.commonsware.android.pagernested;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class PagerFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.pager, container, false);
ViewPager pager=(ViewPager)result.findViewById(R.id.pager);
pager.setAdapter(buildAdapter());
return(result);
}
private PagerAdapter buildAdapter() {
return(new SampleAdapter(getActivity(), getChildFragmentManager()));
}
}
Note how the SampleAdapter
is passed getChildFragmentManager()
from the Fragment
, not getFragmentManager()
. This allows the SampleAdapter
to use fragments, which will be nested inside the outer fragment (PagerFragment
). Beyond that, the rest of the ViewPager
implementation should be the same as if the ViewPager
were hosted by an activity directly.
Upvotes: 2