ViewPager.setCurrentItem Return Wrong Position in PagerAdapter - android

Here's my tabLayoutCode
mTabLayoutBerita.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Log.i("onTabSelected", String.valueOf(tab.getPosition()));
mViewPagerBerita.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
And this is in my PagerAdapter
public class PagerBerita extends FragmentPagerAdapter {
private int mNumOfTabs;
private FragmentBeritaByKategori fragmentBeritaByKategori = null;
private List<KategoriItem> mDataListKategoriBerita;
public PagerBerita(FragmentManager fm, int NumOfTabs, List<KategoriItem> mDataListKategoriBerita) {
super(fm);
this.mNumOfTabs = NumOfTabs;
this.mDataListKategoriBerita = mDataListKategoriBerita;
}
#Override
public Fragment getItem(int position) {
fragmentBeritaByKategori = new FragmentBeritaByKategori(mDataListKategoriBerita.get(position).getId());
return fragmentBeritaByKategori;
}
#Override
public int getCount() {
return mDataListKategoriBerita.size();
}
}
I'm trying to create dynamic tab layout, but when the tab already showed up, i get wrong data because the position i use in PagerAdapter is wrong. I've already use setOffscreenPageLimit and not working, i'm so confuse. Any solution for this case ? Thanks a lot.

You are forgot to add ViewPager to tab layout.
TabLayout tabsLayout = (TabLayout) findViewById(R.id.tabsLayout);
ViewPager viewpager = (ViewPager) findViewById(R.id.viewpager);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
viewpager.setAdapter(adapter);
//Add ViewPager to tab layout.
tabsLayout.setupWithViewPager(viewpager);
viewpager.setOffscreenPageLimit(8);
tabsLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewpager.setCurrentItem(tab.getPosition());
Log.i("TabLayout Position: " + tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
It working fine.

I do like this, is it wrong ?
final CustomViewPager viewPager = findViewById(R.id.pager);
final PagerAdapterBottomNavigation pagerAdapterBottomNavigation = new PagerAdapterBottomNavigation(getSupportFragmentManager(), tab_layout.getTabCount());
viewPager.setAdapter(pagerAdapterBottomNavigation);
viewPager.setCurrentItem(2);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tab_layout));
tab_layout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
tab_layout.getTabAt(2).getIcon().setColorFilter(getResources().getColor(R.color.secondaryTextColor), PorterDuff.Mode.SRC_IN);
tab.getIcon().setColorFilter(getResources().getColor(R.color.secondaryLightColor), PorterDuff.Mode.SRC_IN);
if(tab.getPosition() == 0) {
actionBar.setTitle("Menu");
} else if(tab.getPosition() == 1) {
actionBar.setTitle("News");
} else if(tab.getPosition() == 2) {
actionBar.setTitle("Event");
} else if(tab.getPosition() == 3) {
actionBar.setTitle("Promo");
} else if(tab.getPosition() == 4) {
actionBar.setTitle("Setting");
}
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.getIcon().setColorFilter(getResources().getColor(R.color.secondaryTextColor), PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
My PagerAdapter
public class PagerAdapterBottomNavigation extends FragmentPagerAdapter {
int mNumOfTabs;
private FragmentAllMenu fragmentAllMenu;
private FragmentBerita fragmentBerita;
private FragmentEvent fragmentEvent;
private FragmentSetting fragmentSetting;
private FragmentPromo fragmentPromo;
public PagerAdapterBottomNavigation(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
fragmentAllMenu = new FragmentAllMenu();
return fragmentAllMenu;
case 1:
fragmentBerita = new FragmentBerita();
return fragmentBerita;
case 2:
fragmentEvent = new FragmentEvent();
return fragmentEvent;
case 3:
fragmentPromo = new FragmentPromo();
return fragmentPromo;
case 4:
fragmentSetting = new FragmentSetting();
return fragmentSetting;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
But i check on PagerAdapter getItem(int position), the position wrong but show correct fragment.

Related

call view of activity from tab fragment

I have a main activity which has a tab layout in which there are two framgents.Following is the code for same.
public void setViewPager(){
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
chipGroup.removeAllViews();
utils.createChip(getLayoutInflater(),R.layout.chipview,chipGroup,arrayListFilter);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
Log.d("hgfdgf","+"+tab.getPosition());
if(tab.getPosition()==0){
fragment=new StudyNotes_fragment();
chipGroup.removeAllViews();
utils.createChip(getLayoutInflater(),R.layout.chipview,chipGroup,arrayListFilter);
//filter_iv_booklet.setVisibility(GONE);
}
else if (tab.getPosition()==1){
fragment2=new Specialbooklet_fragment();
chipGroup.removeAllViews();
utils.createChip(getLayoutInflater(),R.layout.chipview,chipGroup,arrayListFilter2);
//filter_iv_booklet.setVisibility(VISIBLE);
}
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
}
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:
for (int i=0;i<=studyM.size()-1;i++){
arrayListFilter.add(studyM.get(i).get(i).getCSubjectName());
}
LayoutInflater li = LayoutInflater.from(context);
HashSet<String> hashSet = new HashSet<String>();
hashSet.addAll(arrayListFilter);
arrayListFilter.clear();
arrayListFilter.addAll(hashSet);
Bundle args = new Bundle();
args.putStringArrayList("array2",arrayListFilter);
args.putSerializable("array4",studyM);
args.putSerializable("tag",makeFragmentName(viewPager.getId(), 1));
fragment.setArguments(args);
return fragment;
case 1:
for (int i=0;i<=specialB.size()-1;i++){
arrayListFilter2.add(specialB.get(i).get(i).getCSubjectName());
}
LayoutInflater li1 = LayoutInflater.from(context);
HashSet<String> hashSet1 = new HashSet<String>();
hashSet1.addAll(arrayListFilter2);
arrayListFilter2.clear();
arrayListFilter2.addAll(hashSet1);
String fragmentTag2 = makeFragmentName(viewPager.getId(), 2);
Bundle args1 = new Bundle();
args1.putSerializable("array", specialB);
args1.putStringArrayList("array2",arrayListFilter2);
args1.putStringArrayList("array3",videosubtitlelist);
args1.putString("tag",fragmentTag2);
fragment2.setArguments(args1);
return fragment2;
//return Specialbooklet_fragment.newInstance(specialB,arrayListFilter2,videosubtitlelist,fragmentTag2);
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
I am using a button which is in toolbar of activity in fragment.I am accessing it in fragment by using getactivity. Below is my code.
rl_filter = activity.findViewById(R.id.rl_filter);
filter_iv = activity.findViewById(R.id.filter_iv);
chipGroup = activity.findViewById(R.id.chipgroup);
applyfilter_tv = activity.findViewById(R.id.applyfilter_tv);
clearfilter_tv = activity.findViewById(R.id.clearfilter_tv);
filter_iv.setOnClickListener(this::onClick);
rl_filter.setOnClickListener(this::onClick);
clearfilter_tv.setOnClickListener(this::onClick);
applyfilter_tv.setOnClickListener(this::onClick);
I am doing same thing in second fragment.My problem is that clicks of only second framgent is working when i am defining the views in both fragments. If i am removing listener and initialisation of buttons from second fragment then first fragment clicks are working. Is there any way i can use the view of activity in both the fragments.

How to hide FAB on a particular fragment

Well I want to remove/hide FAB only on a particular fragment , HISTORY tab in my case .
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
.... (Overriding methods , I didnt do anything here
});
My methods for inflating View Pager
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new HistoryFragment(), "HISTORY");
adapter.addFragment(new TransactionFragment(), "CURRENT");
adapter.addFragment(new FutureFragment(), "FUTURE");
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 android.support.v4.app.Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(android.support.v4.app.Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Where and how should I make changes to my code to Hide my FAB from the HISTORY tab/fragment and show again on other Tabs
I'd think it's as simple as this:
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
if(position == 0) {
// hide FAB
} else {
// show FAB
}
}
}
You can do a lot of cleanup to improve maintenance like assign page numbers to each page like:
private static final int PAGE_HISTORY = 0;
private static final int PAGE_TRANSACTION = 1;
private static final int PAGE_FUTURE = 2;
So instead of if(position == 0) you say if(position == PAGE_HISTORY). That way you don't have to change a lot of code if you ever change your pages around.
You can try setting the OnTabSelectedListener to your TabLayout.
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
yourFAB.setVisibilty(View.GONE);
// or
yourFAB.setVisibilty(View.VISIBLE);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Just add this you your OnPageChangeListener:
#Override
public void onPageSelected(int position) {
if (adapter.getItem(position) instanceof HistoryFragment) fab.hide();
//else fab.show();
}

how to save the view pager fragment instance in android

when i move to another tab, every time its creating new.
am getting tabname and catid from server,
private void setTabTitle() {
Final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
mviewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(jSonTab.size());
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(mviewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mviewPager.setCurrentItem(tab.getPosition()); // Get current clicked Tab Position
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
});
}
public Parcelable saveState() {
return null;
}
class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return MainFragment.newInstance(CatId.get(position), tabName.get(position));
}
#Override
public int getCount() {
return tabName.size();
}
#Override
public CharSequence getPageTitle(int position) {
return tabName.get(position);
}
}
when i change anything in first tab, and go anyother tab, first tab is refreshing and creating new instance,
everytime am calling server to fetch the details for the particular tab
Try setting viewPager.setOfscreenPagelimit(noOfPagesInViewPager);
class ViewPagerAdapter extends FragmentStatePagerAdapter {
Mainfragment mainfragment;
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
mainfragment=new Mainfragment();
}
#Override
public Fragment getItem(int position) {
return mainfragment(CatId.get(position), tabName.get(position));
}
#Override
public int getCount() {
return tabName.size();
}
#Override
public CharSequence getPageTitle(int position) {
return tabName.get(position);
}
}

Tablayout tab with multiple fragment

I am working on an app which use tab layout with 5 tabs. My need is to navigate multiple fragment inside every tab, and open the first fragment when user again reselected the tab. Please help me.
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.scene_tab_selector));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.my_scene_tab_selector));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.conversation_tab_selector));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.notification_tab_selector));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.more_tab_selector));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdaptor adapter = new PagerAdaptor
(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());
tab.getIcon().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
if(tab.getPosition()==4)
{
// pageTitleLabel.setText("My Profile");
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
tab.getIcon().setColorFilter(Color.parseColor("#a8a8a8"), PorterDuff.Mode.SRC_IN);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
My PagerAdaptor is as follows
public class PagerAdaptor extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdaptor(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Tab1ContainerFragment tab1 = new Tab1ContainerFragment();
return tab1;
case 1:
MyCuddllFragment tab2 = new MyCuddllFragment();
return tab2;
case 2:
// CuddllConversationFragment tab3 = new CuddllConversationFragment();
ConversationFragment conversationFragment = new ConversationFragment();
return conversationFragment;
case 3:
// CuddllNotificationsFragment tab4 = new CuddllNotificationsFragment();
Tab4ContainerFragment notificationPageFragment = new Tab4ContainerFragment();
return notificationPageFragment;
case 4:
MyProfileFragment tab5 = new MyProfileFragment();
return tab5;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
public void onTabSelected(TabLayout.Tab tab) {
tab.getIcon().setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_IN);
if(tab.getPosition()==0)
{
viewpager.setCurrentItem(0);
}else if(tab.getPosition()==1)
{
viewpager.setCurrentItem(1);
}else if(tab.getPosition()==2)
{
viewpager.setCurrentItem(2);
}else if(tab.getPosition()==3)
{
viewpager.setCurrentItem(3);
}
}

Tabs with fragment in activity

I have 2 tabs and 2 fragments.I did all for this guide
http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/
but now I see tabs but dont see my fragments.What is the problem?
ViewPagerAdapter:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public ViewPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
switch (position) {
case 0:
Direct tab1 = new Direct();
return tab1;
case 1:
AdventuresFragment tab2 = new AdventuresFragment();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
Activity with using this adapter:
public class TabsActivity extends Activity {
Fragment directFragmentTab = new Direct();
Fragment adventuresFragmentTab = new AdventuresFragment();
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
}
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
() {
#Override
public int getCount() {
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
};
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) {
}
});
}
}
In your activity you are using the PagerAdapter class while your fragment handling class is named ViewPagerAdapter. You want to use the ViewPagerAdapter class instead.

Categories

Resources