Hello everybody
I have a Fragment with a TabLayout with to tabs, I implement the PagerAdapter and everything work fine, the problem is when I go to other option and after that I tap in to the option again the TabLayout appears but empty, I will share with you the code that I wrote for this functionality:
Adapter:
public class DevicePagerAdapter extends FragmentPagerAdapter {
public DevicePagerAdapter(FragmentManager fm){
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:{
return new fragmentDeviceCategory();
}
case 1:{
return new fragmentDeviceRoom();
}
default:{
return null;
}
}
}
#Override
public int getCount() {
return 2;
}
}
Code for one of the Fragments in the TabLayout:
public class fragmentDeviceList extends Fragment {
protected ViewPager viewPager;
public fragmentDeviceList() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setTitle(getResources().getString(R.string.title_devices_list));
}
#Override
public void onResume() {
super.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_device_list, container, false);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.title_tab_by_category)).setIcon(getResources().getDrawable(R.drawable.ic_category_black_36dp, getActivity().getTheme())));
} else {
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.title_tab_by_category)).setIcon(getResources().getDrawable(R.drawable.ic_category_black_36dp)));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.title_tab_by_room)).setIcon(getResources().getDrawable(R.drawable.ic_room_black_36dp, getActivity().getTheme())));
} else {
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.title_tab_by_room)).setIcon(getResources().getDrawable(R.drawable.ic_room_black_36dp)));
}
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) view.findViewById(R.id.pager);
DevicePagerAdapter adapter = new DevicePagerAdapter(getFragmentManager());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
}
An this is the code that I'm using in the main Fragment who is hosting the TabLayout:
public class fragmentDeviceList extends Fragment {
protected ViewPager viewPager;
public fragmentDeviceList() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setTitle(getResources().getString(R.string.title_devices_list));
}
#Override
public void onResume() {
super.onResume();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_device_list, container, false);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.title_tab_by_category)).setIcon(getResources().getDrawable(R.drawable.ic_category_black_36dp, getActivity().getTheme())));
} else {
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.title_tab_by_category)).setIcon(getResources().getDrawable(R.drawable.ic_category_black_36dp)));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.title_tab_by_room)).setIcon(getResources().getDrawable(R.drawable.ic_room_black_36dp, getActivity().getTheme())));
} else {
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.title_tab_by_room)).setIcon(getResources().getDrawable(R.drawable.ic_room_black_36dp)));
}
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) view.findViewById(R.id.pager);
DevicePagerAdapter adapter = new DevicePagerAdapter(getFragmentManager());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
}
Note: When I debugged the code I note that the method `onCreateView` in the `fragmentDeviceList` (The fragment that it is hosted the TabLayout) it is executed, but the method `onCreateView` of the fragment `fragmentDeviceCategory` is not fired.
To use the tabs inside a Fragment you should use ChildFragmentManager.
The line:
DevicePagerAdapter adapter = new DevicePagerAdapter(getFragmentManager());
should be:
DevicePagerAdapter adapter = new DevicePagerAdapter(getChildFragmentManager());
FragmentPagerAdapter is a valid use for just two fragments because it keeps them in memory. FragmentStatePagerAdapter is intended for a larger number of fragments.
Also TabLayout has a method setupWithViewPager that will:
This method will:
Add a ViewPager.OnPageChangeListener that will forward events to this TabLayout.
Populate the TabLayout's tabs from the ViewPager's PagerAdapter.
Set our TabLayout.OnTabSelectedListener which will forward selected events to the ViewPager
You can use it instead of manually adding tabs.
I got the solution for the problem, the solutions is very simple, I thought that I can use as Adapter for the ViewPage FragmentPagerAdapter because i want to show just fragments, but this class remain the state of the fragment so the nested fragment don't is initialized again, so I changed my adapter to FragmentStatePagerAdapter and now is working properly.
Thank you all
Related
I have multiple fragment and all are show some news
Problem is that when I run my app all fragment load and get all fragment data from server but I want to get data when I move on that particular fragment so please help me
My Code is below
MainActivity.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setToolbar();
initView();
}
private void initView() {
TabLayout tabLayout=(TabLayout)findViewById(R.id.tablayout);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
addTabs(tabLayout,viewPager);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
private void addTabs(TabLayout tabLayout, final ViewPager viewPager) {
final PageAdapter pageAdapter = new PageAdapter(getSupportFragmentManager(), 5);
tabLayout.addTab(tabLayout.newTab().setText(NewsConstant.HeadLines));
tabLayout.addTab(tabLayout.newTab().setText(NewsConstant.Sports));
tabLayout.addTab(tabLayout.newTab().setText(NewsConstant.Health));
tabLayout.addTab(tabLayout.newTab().setText(NewsConstant.India));
tabLayout.addTab(tabLayout.newTab().setText(NewsConstant.World));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setAdapter(pageAdapter);
viewPager.setOffscreenPageLimit(5);
}
PageAdapter.java
public class PageAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PageAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
return NewsFragment.newInstance(position,position+"");
}
#Override
public int getCount() {
return mNumOfTabs;
}
NewFragment.java
public class NewsFragment extends Fragment {
private RecyclerView recyclerView;
public static NewsFragment newInstance(int index,String title) {
NewsFragment fragment = new NewsFragment();
Bundle args = new Bundle();
args.putInt(NewsConstant.INDEX,index);
args.putString(NewsConstant.TITLE,title);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_news_list, container, false);
initView(view);
getDataFromServer(); // Here i get data and display
return view;
}
For Ex.
I use TabLayout, ViewPager in Activity to load Fragments
I have 3 TAB like Headline | Sports | Hollywood
I use same fragment for all TAB
so when I click on Hollywood TAB then get data from server and display at that recyclerView
I faced same problem once
Try using
private boolean isViewShown = false;
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getView() != null && isVisibleToUser) {
isViewShown = true; // fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
fetchData();
} else {
isViewShown = false;
} }
Call your Api or what ever you want to see when you reached the fragment here inside
View pager actually loads previous, current and next pages simultaneously. This is to have a seamless experience while swiping. This can be controlled using the approach mentioned by #Jius Lukose
or please refer to the answer
How can make my ViewPager load only one page at a time ie setOffscreenPageLimit(0);
I have 2 Tabs as fragments in a ViewPager in an Activity
When I tap the second tab in the layout, the OnTabUnselected method works.
However, when I slide the screen from one tab to another, the method isn't called.
How do I achieve this calling of method by both means "Tapping as well as in a Sliding Gesture"
My Activity class is:
public class OrderActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private FloatingActionButton printAction;
ViewPagerAdapter adapter;
private Boolean exit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_icon_text_tabs);
TypefaceUtil.overrideFont(getApplicationContext(), "serif", "fonts/opensans.tff");
//TypefaceUtil.overrideFont(getApplicationContext(), "arial", "fonts/opensans.tff");
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
//setupTabIcons();
printAction = (FloatingActionButton) findViewById(R.id.float_print);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Toast.makeText(getApplicationContext(),"onTabSelected",Toast.LENGTH_LONG).show();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
String ac = null;
int pos = viewPager.getCurrentItem();
Fragment activeFragment = adapter.getItem(pos);
if(pos==0){
ac= ((PersonalDetailFragment)activeFragment).getXmlValue();
}
Toast.makeText(getApplicationContext(),ac,Toast.LENGTH_LONG).show();
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
Toast.makeText(getApplicationContext(),"onTabReselected",Toast.LENGTH_LONG).show();
}
});
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new PersonalDetailFragment(), "Personal");
adapter.addFrag(new OrderItemsFragment(), "Invoice");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Fragment A:
public class FragmentA extends Fragment {
private EditText custName;
public PersonalDetailFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.personal_detail_fragment, container, false);
custName = (EditText) view.findViewById(R.id.customerContactEditText);
return view;
}
public String getXmlValue(){
return custName.getText().toString();
}
}
Fragment B:
public class FragmentB extends Fragment {
private EditText contactNo;
public PersonalDetailFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.personal_detail_fragment, container, false);
contactNo = (EditText) view.findViewById(R.id.customerContactEditText);
return view;
}
}
You can use the ViewPager.addOnPageChangeListener() method to register a listener and get notified about changing the current tab with a pager swipe.
There is a really nice tutorial here.
In your fragment you can use a method named setVisibilityHint that is called every time the visibility of the fragment has been changed. There is a boolean parameter that can be true or false depending if the fragment is visible or not
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}
I've built an Android app which uses fragments and action bar to create a tab layout. The app is made up of:
MainActivity.java
PagerAdapter.java
Tab1Fragment.java
Tab2Fragment.java
activity_main.xml
fragment_tab_1.xml
fragment_tab_2.xml
I have this working and I can switch between tabs. My question is how do I control the content of each tab? Obviously I can add my objects to each xml layout but where should I be identifying these objects in my java code? Should I be controlling the content in MainActivity.java or within each separate Fragment.java?
MainActivity.java:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Questions"));
tabLayout.addTab(tabLayout.newTab().setText("Ask a Question"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Tab1Fragment.java:
public class Tab1Fragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_tab_1, container, false);
}
}
PagerAdapter.java:
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab1Fragment tab1 = new Tab1Fragment();
return tab1;
case 1:
Tab2Fragment tab2 = new Tab2Fragment();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
You should reference all of the views within the Fragment code. The views within are defined in that specific Fragment's xml layout file, so the Activity will not be able to reference them easily.
Example:
public class Tab1Fragment extends Fragment {
Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_1, container, false);
button = (Button) view.findViewById(R.id.button);
//Get all views here
return view; //Must return a view
}
}
I am not clearly understand what you ask but i think you are asking where to code for the specific tabview the answer is in Tab1Fragment and Tab2Fragment.
Hi I'm making an app with A fragment and few child fragment inside it using tablayout and viewpager. The problem is all my child fragment (from Tablayout) always execute (load all the code inside whenever user click the parent fragment. How to get the child fragment only load whenever the the user slide to it (for example I have 2 tab, content in tab 2 only load when user slide to tab 2)
Here is my parent fragment code
public class ManageEventFragment extends Fragment {
public ManageEventFragment() {
// Required empty public constructor
}
TabLayout tabLayout;
ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View viewFragment = inflater.inflate(R.layout.fragment_manage_event, container, false);
viewPager = (ViewPager) viewFragment.findViewById(R.id.viewPager);
tabLayout = (TabLayout) viewFragment.findViewById(R.id.tabLayout);
viewPager.setAdapter(new CustomAdapter(getChildFragmentManager(), getContext()));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
return viewFragment;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// tabLayout.setupWithViewPager(viewPager);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
});
if (ViewCompat.isLaidOut(tabLayout)) {
tabLayout.setupWithViewPager(viewPager);
} 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) {
tabLayout.setupWithViewPager(viewPager);
tabLayout.removeOnLayoutChangeListener(this);
}
});
}
super.onActivityCreated(savedInstanceState);
}
//TabLayout and ViewPager class
private class CustomAdapter extends FragmentPagerAdapter {
private String fragments[] = {"Edit Event", "Create Event"};
public CustomAdapter(FragmentManager fragmentManager, Context context) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new EditEventFragment();
case 1:
return new CreateEventFragment();
default:
return null;
}
}
#Override
public int getCount() {
return fragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
return fragments[position];
}
}
}
And my child fragment code. I want these code only execute whenever the user slide to the child tab. Any help is much appreciate, Thanks
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Initializing our listEvents list
listEvents = new ArrayList();
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
adapter = new EventAdapterEdit(getContext(),listEvents);
recyclerView.setAdapter(adapter);
requestQueue = Volley.newRequestQueue(getContext());
adapter = new EventAdapterEdit(getContext(),listEvents);
recyclerView.setAdapter(adapter);
getEventDetailRespond(requestQueue);
#Override public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}
you could use above method within your fragment that is within your ViewPager Adapter
if(isVisibleToUser){//dosomething when the fragment is visible}
else{//dosomething else.}
be aware to do not initialize views there or anything rather, init your views within onViewCreated and call the method that you wanna execute on setUserVisibleHint. another ugly way is to add a scroll listener to your ViewPager and get the current item position and trigger an action that is within the fragment. to get the fragment from the ViewPager Adapter you can do such :
MyFragment frag = (MyFragment) pager.getAdapter().instantiateItem(pager, position);
then you could call a method that is within MyFragment
The Viewpager by default loads the adjacent fragment to ensure make the app smooth, so that when the user swipe to the fragments (already loaded) it is there. To change is default behavior, use
viewpager.setOffscreenPageLimit(int limit) where limit is how many fragment next to the one you are on will be preloaded.
Hope this helps
Hi I have a TabLayout and ViewPager inside a fragment. But I can not slide beetween tab to come to child fragment (Working normally when in Activity but not work in fragment).
Here is my code for Tablayout inside fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflateView = inflater.inflate(R.layout.fragment_assign_beacon_to_event, container, false);
//Viewpager and TabLayout
viewPager = (ViewPager)inflateView.findViewById(R.id.viewPager);
viewPager.setAdapter(new CustomAdapter(getFragmentManager(), getContext()));
tabLayout = (TabLayout)inflateView.findViewById(R.id.tabLayout);
// Inflate the layout for this fragment
return inflateView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
});
Any here is my Custom Adapter class
private class CustomAdapter extends FragmentPagerAdapter {
private String fragments[] = {"Assign Event", "Manage Event"};
public CustomAdapter(FragmentManager supportFragmentManager, Context applicationContext) {
super(supportFragmentManager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// return new AssignEventToBeacon();
return new Test1();
case 1:
return new ManageEventAssigned();
default:
return null;
}
}
#Override
public int getCount() {
return fragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
return fragments[position];
}
}
I doubt i have problem with this line:
viewPager.setAdapter(new CustomAdapter(getFragmentManager(), getContext()));
Anyhelp is much appreciate, thanks
I have done a similar project and here is my code for the fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.outer_fragment, container, false);
setHasOptionsMenu(true);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
if (viewPager != null) {
setupViewPager(viewPager);
}
Log.v("Layout","Tabs");
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#FFFFFF"));
tabLayout.setTabTextColors(Color.parseColor("#707070"), Color.parseColor("#FFFFFF"));
assert viewPager != null;
tabLayout.setupWithViewPager(viewPager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getChildFragmentManager());
adapter.addFragment(new Tab1Fragment(), "PHOTOS");
adapter.addFragment(new Tab2Fragment(), "HI-FIVES");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
You need to use getChildFragmentManager() in Fragment instead of getFragmentManager().
From getChildFragmentManager() documentation
Return a private FragmentManager for placing and managing Fragments
inside of this Fragment.
From getFragmentManager() documentation
Return the FragmentManager for interacting with fragments associated
with this fragment's activity.
In simple words,
Use getChildFragmentManager() for Child Fragments
Use getFragmentManager() for Fragments inside Activity
One can see #this answer for complete code.