How to set a ViewPager inside a Fragment
Starting in Android 4.2, there are nested fragments.http://developer.android.com/about/versions/android-4.2.html#NestedFragments The support library now also includes support for this for older Android versions.
So you can do something like this:
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
mViewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
}
Full implementation available here: https://github.com/marcoRS/nested-fragments/tree/master/src/com/burnside/digital/nestedfragments
How to put viewpager inside fragment in android?
To have a ViewPager
be in a fragment, and to have fragments be the pages in that ViewPager
, you need to use nested fragments. If your minSdkVersion
is 17 or higher, the native implementation of fragments supports nested fragments. Otherwise, you will need to use the support-v13
(or support-v4
) backport of fragments.
Then, you just need to give getChildFragmentManager()
to your FragmentPagerAdapter
or FragmentStatePagerAdapter
:
/***
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()));
}
}
(from this sample project)
Add ViewPager in Fragment in Android
In FirstFragment
, Use this code and try
public View view; // declare view as global variable
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
if(view == null){
view = inflater.inflate(R.layout.first_fragment, null);
mViewPager = (ViewPager) view.findViewById(R.id.view_pager);
ViewPagerAdapter adapter = new ViewPagerAdapter(mainActivity.getSupportFragmentManager());
mViewPager.setAdapter(adapter);
}
return view;
}
As Divyesh comment has good suggestion there is also need to add
mViewPager.setOffscreenPageLimit(3);
ViewPager inside Fragment
That's a common bug with design support library related to ViewCompat
.
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setupViewPager(viewPager);
// after you set the adapter you have to check if view is laid out, i did a custom method for it
if (ViewCompat.isLaidOut(tabLayout)) {
setViewPagerListener();
} else {
tabLayout.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
setViewPagerListener();
tabLayout.removeOnLayoutChangeListener(this);
}
});
}
}
private void setViewPagerListener() {
tabLayout.setupWithViewPager(viewPager);
// use class TabLayout.ViewPagerOnTabSelectedListener
// note that it's a class not an interface as OnTabSelectedListener, so you can't implement it in your activity/fragment
// methods are optional, so if you don't use them, you can not override them (e.g. onTabUnselected)
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
@Override
public void onTabReselected(TabLayout.Tab tab) {
super.onTabReselected(tab);
}
@Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
}
});
}
Also, holding onto a list of Fragment instances in a ViewPagerAdapter (especially FragmentPagerAdapter) will most likely cause crashes after process death in production, so your adapter should look like this:
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
@Override
public Fragment getItem(int position) {
if(position == 0) return new TopTracks();
if(position == 1) return new WorldCharts();
if(position == 2) return new NewMusic();
if(position == 3) return new AfricaHot();
if(position == 4) return new Playlists();
if(position == 5) return new Recommended();
throw new IllegalStateException("Unexpected position " + position);
}
@Override
public int getCount() {
return 6;
}
@Override
public CharSequence getPageTitle(int position) {
if(position == 0) return "Top Tracks";
if(position == 1) return "World Charts";
if(position == 2) return "New Music";
if(position == 3) return "Africa Hot";
if(position == 4) return "Playlists";
if(position == 5) return "Recommended";
throw new IllegalStateException("Unexpected position " + position);
}
}
How can I put a ViewPager inside a Fragment?
Option #1: Use nested fragments. That will require you to have your minSdkVersion
set to 17 or higher, or you will have to use the fragments backport from the Android Support Package. This sample app demonstrates using the backport.
In short, your fragment that hosts the ViewPager
will pass getChildFragmentManager()
to your FragmentPagerAdapter
or FragmentStatePagerAdapter
:
/***
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()));
}
}
Option #2: Write your own PagerAdapter
that does not use fragments (or have anything inside of it managed by fragments). Then, you do not need nested fragments anymore, and you can just use your custom PagerAdapter
with a ViewPager
that is hosted by a fragment.
How to implement a viewpager inside of a fragment?
I use this one hope it help you too : https://github.com/thecodepath/android_guides/wiki/ViewPager-with-FragmentPagerAdapter
So you can use this one: https://github.com/astuetz/PagerSlidingTabStrip
Calling ViewPager inside a Fragment
Root cause
In view_pager_fragment.xml
file, you declare a ViewPager2
with id sliderViewPager
but in ViewPagerFragment
class, you use a ViewPager
variable and assign a view with id viewPagerFragment
to it.
Solution
Step 1. Change fragment_view_pager.xml
to:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">
<androidx.viewpager.widget.ViewPager
android:id="@+id/sliderViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_weight="1">
</androidx.viewpager.widget.ViewPager>
<LinearLayout
android:id="@+id/dotsLayout"
android:layout_width="wrap_content"
android:layout_height="66dp"
android:layout_gravity="center"
android:layout_weight="1"
android:orientation="horizontal">
</LinearLayout>
</LinearLayout>
Step 2. In ViewPagerFragment
class, change your code from
viewpager = (ViewPager) view.findViewById(R.id.viewPagerFragment);
to
viewpager = (ViewPager) view.findViewById(R.id.sliderViewPager);
Related Topics
Android - Supportmapfragment with Googlemaps API 2.0 Giving Illegalargumentexception
Android: How to Make an Activity Return Results to the Activity Which Calls It
Android - How to Enable Autostart Option Programmatically in Xiaomi Devices
How to Send JSON Object to Server Using Volley in Android
How to Get the Fragment Instance from the Fragmentactivity
How to Resolve Java.Util.Zip.Zipexception
Listfragment Onlistitemclick Not Being Called
How to Determine If an Android Service Is Running in the Foreground
Popupwindow $Badtokenexception: Unable to Add Window -- Token Null Is Not Valid
Android Toggle Button Custom Look
Android Resources$Notfoundexception: Resource Id #0X7F030027
Getting MAC Address in Android 6.0
How to Join Png with Alpha/Transparency in a Frame in Realtime
Firebase Admin Sdk for Android, Methods Not Found
How to Set Shadow to a View in Android
Starting Frame-By-Frame Animation
The Process of the Service Is Killed After the Application Is Removed from the Application Tray