tabs fragment isn't displayed after reload - android

I'm creating an app with view pager and tabs:
At the first time clicked on "menu" item in the bottom navigation the text frag1, frag2 and frag3 are displayed as expected on the screen by clicking on the tabs and swiping (viewpager).
See image below:
But when I click an another item (e.g. home) and go back to "menu" item the text frag 1 and etc. are not display. See image below:
MenuFragment with viewpageradapter:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu, container, false);
setHasOptionsMenu(true);
ButterKnife.bind(this, view);
FragmentManager fragManager = myContext.getSupportFragmentManager();
viewPagerAdapter = new ViewPagerAdapter(fragManager);
viewPagerAdapter.addFragment(new MenuRecyclerViewFragment(), "FRAG1"); // `new MenuRecyclerViewFragment()` should be inside `FragmentPagerAdapter.getItem()`
viewPagerAdapter.addFragment(new MenuRecyclerViewFragment(), "FRAG2"); // `new MenuRecyclerViewFragment()` should be inside `FragmentPagerAdapter.getItem()`
viewPagerAdapter.addFragment(new MenuRecyclerViewFragment(), "FRAG3"); // `new MenuRecyclerViewFragment()` should be inside `FragmentPagerAdapter.getItem()`
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
viewPager.setOnPageChangeListener(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;
}
class ViewPagerAdapter extends FragmentPagerAdapter {
public final List<Fragment> mFragmentList = new ArrayList<>(); // this line can cause crashes
public final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = mFragmentList.get(position);
Bundle bundle = new Bundle();
bundle.putString("text", mFragmentTitleList.get(position));
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment); // this line can cause crashes
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
MenuRecylerViewFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_recycler_view, container, false);
ButterKnife.bind(this, view);
Bundle bundle = this.getArguments();
if (bundle != null) {
String value = bundle.getString("text", "test");
textView.setText(value);
}
return view;
}

The second time you land to this fragment, getArguments() is not longer not null.
Use the savedInstanceState bundle instead.

Your ViewPagerAdapter class need to be extend by FragmentStatePagerAdapter instead of FragmentPagerAdapter.
Look into more details of FragmentStatePagerAdapter.

1.) Fragments hosted by a ViewPager should be created by FragmentPagerAdapter.getItem().
public class ViewPagerAdapter extends FragmentPagerAdapter {
public ViewPagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
#Override
public Fragment getItem(int position) {
if(position == 0) return new MenuRecyclerViewFragment();
if(position == 1) return new MenuRecyclerViewFragment();
if(position == 2) return new MenuRecyclerViewFragment();
throw new IllegalStateException("Unexpected position " + position);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if(position == 0) return "FRAG1";
if(position == 1) return "FRAG2";
if(position == 2) return "FRAG3";
throw new IllegalStateException("Unexpected position " + position);
}
}
2.) ViewPagers inside a Fragment (hosting Fragments) should be given getChildFragmentManager() instead of context.getSupportFragmentManager() for it to work.

Related

Not getting current selected Tab position in android tablayout

I am creating a Tab based application where the user can create tabs by clicking a button and can delete the tabs by clicking another button. I implemented this using Tab layout, Fragments and Viewpager.
I am able to get the current tab position when new tab is created by the function setuptablyout function. But when i clicked another tab ie moving to other tabs I am not able to toast the position.
I found that using tabLayout.addOnTabSelectedListener I can get the position, while that doesn't work here.
my Activity Code is:
public class MainActivity extends AppCompatActivity{
TextView textView;
private TabLayout tabLayout;
public static ViewPager viewPager;
public static ViewPagerAdapter adapter;
private ImageView add;
int selectedTabPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.my_viewpager);
tabLayout = (TabLayout) findViewById(R.id.my_tab_layout);
add= (ImageView) findViewById(R.id.imageButtonAdd1);
adapter = new ViewPagerAdapter(getSupportFragmentManager(), MainActivity.this, viewPager, tabLayout);
viewPager.setAdapter(adapter);
createFirstFragment("POS "+adapter.getCount());
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Toast.makeText(getApplicationContext(),"Pos onTabSelected: "+ tabLayout.getSelectedTabPosition(),Toast.LENGTH_SHORT).show();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(adapter.getCount() > 4){
Toast.makeText(MainActivity.this, "Only 5 Tabs allowed", Toast.LENGTH_SHORT).show();
}
else {
Bundle bundle = new Bundle();
bundle.putString("data", "POS "+adapter.getCount());
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, "POS "+adapter.getCount());
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
Log.e("adapter.getCount()",String.valueOf(adapter.getCount()));
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
}
});
}
public void createFirstFragment(String pagename) {
Bundle bundle = new Bundle();
bundle.putString("data", pagename);
FragmentChild fragmentChild = new FragmentChild();
fragmentChild.setArguments(bundle);
adapter.addFrag(fragmentChild, pagename);
adapter.notifyDataSetChanged();
if (adapter.getCount() > 0) tabLayout.setupWithViewPager(viewPager);
Log.e("adapter.getCount()",String.valueOf(adapter.getCount()));
viewPager.setCurrentItem(adapter.getCount() - 1);
setupTabLayout();
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
Toast.makeText(MainActivity.this, "selectedTabPosition --> "+selectedTabPosition, Toast.LENGTH_SHORT).show();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(adapter.getTabView(i));
}
}
}
ViewPager class:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final ArrayList<Fragment> mFragmentList = new ArrayList<>();
private final ArrayList<String> mFragmentTitleList = new ArrayList<>();
Context context;
ViewPager viewPager;
TabLayout tabLayout;
int selectedTabPosition;
PreferenceHelper prefs;
private Map<Integer, String> mFragmentTags;
private FragmentManager mFragmentManager;
private boolean doNotifyDataSetChangedOnce = false;
public ViewPagerAdapter(FragmentManager manager, Context context, ViewPager viewPager,
TabLayout tabLayout) {
super(manager);
this.context = context;
this.viewPager = viewPager;
this.tabLayout = tabLayout;
mFragmentTags = new HashMap<Integer, String>();
prefs = new PreferenceHelper(context);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
if (doNotifyDataSetChangedOnce) {
doNotifyDataSetChangedOnce = false;
notifyDataSetChanged();
}
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void removeFrag(int position) {
removeTab(position);
Fragment fragment = mFragmentList.get(position);
mFragmentList.remove(fragment);
mFragmentTitleList.remove(position);
//destroyFragmentView(viewPager, position, fragment);
notifyDataSetChanged();
Log.e("getCount()", String.valueOf(getCount()));
if (getCount() > 0)
tabLayout.setupWithViewPager(viewPager);
setupTabLayout();
}
public View getTabView(final int position) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab_item, null);
TextView tabItemName = (TextView) view.findViewById(R.id.textViewTabItemName);
ImageView tabItemAvatar =
(ImageView) view.findViewById(R.id.imageViewTabItemAvatar);
ImageButton remove = (ImageButton) view.findViewById(R.id.imageButtonRemove);
if(getCount() == 1){
remove.setVisibility(View.INVISIBLE);
}
else{
remove.setVisibility(View.VISIBLE);
}
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Remove", "Remove");
if(getCount() != 1){
removeFrag(position);
}
else{
// Toast.makeText("Atleast One Tab is requied")
}
}
});
tabItemName.setText(mFragmentTitleList.get(position));
tabItemName.setTextColor(context.getResources().getColor(android.R.color.background_light));
tabItemAvatar.setImageResource(R.drawable.boy);
return view;
}
public void setupTabLayout() {
selectedTabPosition = viewPager.getCurrentItem();
Toast.makeText(context, "selectedTabPosition --> "+selectedTabPosition, Toast.LENGTH_SHORT).show();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
tabLayout.getTabAt(i).setCustomView(getTabView(i));
}
}
public void removeTab(int position) {
if (tabLayout.getChildCount() > 0 && tabLayout!=null) {
tabLayout.removeTabAt(position);
prefs.remove("POS"+position);
}
}
/*#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (mCurrentFragment != object) {
mCurrentFragment = (Fragment) object;
}
super.setPrimaryItem(container, position, object);
}*/
#Override
public Object instantiateItem(ViewGroup container, int position) {
Object object = super.instantiateItem(container, position);
if (object instanceof Fragment) {
Fragment fragment = (Fragment) object;
String tag = fragment.getTag();
mFragmentTags.put(position, tag);
}
return object;
}
public Fragment getFragment(int position) {
Fragment fragment = null;
String tag = mFragmentTags.get(position);
if (tag != null) {
fragment = mFragmentManager.findFragmentByTag(tag);
}
return fragment;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
I am getting this weird behaviour that whenever I create new tabs the onTabSelected functions are calling multiple time that even when I create 3rd tab onTabslected toast shows Pos onTabSelected: 0,1 and not the just 2nd position which is supposed to be the 2nd position. What can I do to solve this?
My intention is to get some unique tab id so that I can identify each tab separately
you just create the newInstance constructor for creating fragment with arguments
in your FragmentChild
public static FragmentChild newInstance(int page, String title) {
FragmentChild fragmentChild = new FragmentChild ();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentChild.setArguments(args);
return fragmentChild;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
TextView tvLabel = (TextView) view.findViewById(R.id.tvLabel);
tvLabel.setText(page + " -- " + title);
return view;
}
And then after in adapter class change this.
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
to
#Override
public Fragment getItem(int position) {
return FragmentChild.newInstance(position, "Page # 1");
}
I have not tested this code but, I think this code will help you to get your unique tab id..
test this code and let me know if it works

TabLayout addOnTabSelectedListener is not working properly when I reopen the application

I am working with TabLayout which shows tab icon red according to fragment selected in ViewPager. But I have been facing this problem for 2 weeks and I have been searching a lot to resolve this issue.
The problem is if I am at fragment user account and when I close the application, my user tab icon is selected. Now when I reopen the application fragment, my tab restaurant is loaded, but the user account tab icon is still selected, although restaurant tab icon should be selected.
I have attached screenshots for reference:
user account image
restaurant image after re open
public class PagerMainActivity extends Fragment {
//This is our tablayout
public TabLayout tabLayout;
public static CustomViewPager viewPager;
AdapterPager adapter;
public int tabIconColor_Selected;
public int tabIconColor_DeSelected;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// tabSelection();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_pager, container, false);
tabLayout = (TabLayout) v.findViewById(R.id.tab_layout);
viewPager = v.findViewById(R.id.pager);
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.restaurent).setText("Restaurant"));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.order).setText("Order"));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.deals).setText("Deals"));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.account).setText("Account"));
viewPager = v.findViewById(R.id.pager);
adapter = new AdapterPager(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
adapter.getRegisteredFragment(viewPager.getCurrentItem());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
viewPager.setAllowedSwipeDirection(SwipeDirection.none);
// setupTabIcons();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
#Override
public void onTabSelected(TabLayout.Tab tabSelected)
{
viewPager.setCurrentItem(tabSelected.getPosition());
if(UserAccountFragment.LOG_OUT_FLAG || UserAccountFragment.LOG_IN_FLAG){
tabIconColor_Selected = ContextCompat.getColor(getContext(), R.color.colorDeal);
tabSelected.getIcon().setColorFilter(tabIconColor_Selected, PorterDuff.Mode.SRC_IN);
UserAccountFragment.LOG_OUT_FLAG=false;
UserAccountFragment.LOG_IN_FLAG=false;
}
tabIconColor_Selected = ContextCompat.getColor(getContext(), R.color.colorRed);
tabSelected.getIcon().setColorFilter(tabIconColor_Selected, PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabUnselected(TabLayout.Tab tabSelected){
viewPager.setCurrentItem(tabSelected.getPosition());
tabIconColor_DeSelected = ContextCompat.getColor(getContext(), R.color.colorDeal);
tabSelected.getIcon().setColorFilter(tabIconColor_DeSelected, PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabReselected(TabLayout.Tab tabSelected){
}
});
return v;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
Adapter
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
int mNumOfTabs;
public AdapterPager(FragmentManager fragmentManager, int tabCount) {
super(fragmentManager);
this.mNumOfTabs=tabCount;
}
#Override
public Fragment getItem(int position) {
Fragment fm=null;
switch (position) {
case 0:
fm = new RestaurantsFragment();
break;
case 1:
fm = new OrdersFragment();
break;
case 2:
fm = new DealsFragment();
break;
case 3:
fm = new UserAccountFragment();
break;
}
return fm;
}
#Override
public int getCount() {
return mNumOfTabs;
}
/* #Override
public Parcelable saveState() {
// Do Nothing
return saveState();
}*/
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
Your views and solution will be appreciated. Thanks in advance

How to refresh the Pager tab fragment in android?

I have to refresh the fragment when I swipe to another fragment from the Tab.
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
mBinding = DataBindingUtil.inflate(inflater, R.layout.manage_work_shop_act, container, false);
mBinding.layout.title.setText(getString(R.string.d_manage_my_staff));
mBinding.tabs.setupWithViewPager(mBinding.viewpager);
setupViewPager(mBinding.viewpager);
mBinding.layout.nav.setVisibility(View.GONE);
mBinding.layout.navMenu.setVisibility(View.VISIBLE);
mBinding.layout.navMenu.setOnClickListener(view -> openDrawer());
return mBinding.getRoot();
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
int limit = (adapter.getCount() > 1 ? adapter.getCount() - 1 : 1);
adapter.addFragment(new MechanicListFragment(), getString(R.string.d_manage_my_staff));
adapter.addFragment(new MechanicNewFragment(), getString(R.string.new_frag));
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(limit);
adapter.notifyDataSetChanged();
}
My Adapter is like this
public 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 addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
I tried all the ways to refresh my fragment.
If I swipe the tab or click the another tab then I need to refresh the visible tab again.
In my current fragment did not refresh.
please help me to override from this issue.
Try using Fragment state pager adapter than fragment adapter when you have to refresh tabs in your adapdter.
FragmentPagerAdapter stores the previous data which is fetched from the adapter while FragmentStatePagerAdapter takes the new value from the adapter everytime it is executed.
There's onHiddenChanged method in the fragment.
Called when the hidden state (as returned by isHidden() of the
fragment has changed. Fragments start out not hidden; this will be
called whenever the fragment changes state from that.
override the onHiddenChanged method in each of your tab fragment and if is not hidden do the refreshing. For example:
class YourFragment extends Fragment {
#Override public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (!hidden) {
//you can refresh here now
}
}
}

Catch the changing of slide in a ViewPager

I have implemented a ViewPager in order to swipe between two Fragments like such:
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.statistics_general_vp, container, false);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
mStatisticsPagerAdapter = new StatisticsPagerAdapter(getActivity().getSupportFragmentManager());
mViewPager.setAdapter(mStatisticsPagerAdapter);
return view;
}
public class StatisticsPagerAdapter extends FragmentStatePagerAdapter {
public StatisticsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
return new GeneralStatistics();
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
But for now my two slides display the same Fragment.
How may I have slide 1 display Fragment 1 and slide 2 Fragment 2?
have u created fragment1 and fragment 2 seperately?? if yes then do this - in activity holding these two fragments.
private void createViewPager(ViewPager viewPager) {
Log.d("activity", "viewpager");
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new Fragment1(), "");
adapter.addFrag(new Fragment2(), "");
viewPager.setAdapter(adapter);
}
create fragment like this -
public class Fragment1 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.transaction_layout, container, false);
return v;
}
}
create viewpager like this -
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);
}
}
or if you want to make tab with icons use this method -
private void createTabIcons() {
Log.d("activity", "createtabicons");
TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.tab_item2, null);
tabOne.setText("QR Scan");
tabOne.setTypeface(MRR);
tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.image1, 0, 0);
tabOne.setCompoundDrawablePadding(5);
tabLayout.getTabAt(0).setCustomView(tabOne);
tabLayout.getTabAt(0).getCustomView().setSelected(true);
TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.tab_item2, null);
tabTwo.setText("Mobile No.");
tabTwo.setTypeface(MRR);
tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.image3, 0, 0);
tabLayout.getTabAt(1).setCustomView(tabTwo);
tabTwo.setCompoundDrawablePadding(5);
}
Hello i show you what i doing, i got 2 fragments in mainActivity
private void addFragments() {
List<Fragment> fragments = new ArrayList<>();
chatFragment = new ChatFragment();
remoteFragment = new RemoteFragment();
fragments.add(remoteFragment);
fragments.add(chatFragment);
MyPageAdapter adapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.getTabAt(TAB_REMOTE_POSITION)
.setIcon(getDrawable(R.drawable.ic_settings_remote_white_24dp));
tabLayout.getTabAt(TAB_SOCIAL_POSITION)
.setIcon(getDrawable(R.drawable.ic_group_white_24dp));
}
Here is my adapter:
class MyPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(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();
}
}
and on OnCreate u should
addFragments();
also i bind the views with ButterKnife
#Bind(R.id.view_pager)
ViewPager viewPager;
#Bind(R.id.tab_layout)
TabLayout tabLayout;
but u can static implement this with android
And remember that u have listeners:
private void pageChangeListener() {
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService
(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
});
}

TabLayout with ViewPager not working inside fragment Android

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.

Categories

Resources