How to handle selected, reselected tabs using SlidingTabLayout and SlidingTabStrip? - android

I'm working in an application that uses SlidingTabLayout and SlidingTabStrip and what I want to do is handle when I select a tab and the fragment is changed.
I have read something about ViewPager.OnPageChangeListener and ViewPager.SimpleOnPageChangeListener and tried both, but none of them seems to work and don't know why.

Did you set the ViewPager for your SlidingTabLayout?
//Get reference to SlidingTabLayout and ViewPager from layout
mSlidingTabLayout.setViewPager(mPager);
ViewPager.SimpleOnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
pageSelected = position;
}
};
mSlidingTabLayout.setOnPageChangeListener(pageChangeListener);
mPager.setCurrentItem(pageSelected);
mPager.setAdapter(mAdapter); //Set your FragmentPagerAdapter

Related

SlidingTabLayout and ViewPager: how to load the current fragment and not the adjacent one at the same time?

I am trying to implement a sliding tab layout that and each fragment should only load when the tab is selected instead i get the adjacent fragment loading, I have tried setOffScreenPageLimit(1) as my code shows but still the adjacent fragment gets loaded any assistance please ???
private SlidingTabLayout tabLayout;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
viewPager.setOffscreenPageLimit(1);
tabLayout = (SlidingTabLayout) findViewById(R.id.tabs);
if (tabLayout != null) {
tabLayout.setViewPager(viewPager);
tabLayout.setDistributeEvenly(true);
tabLayout.setSelectedIndicatorColors(R.color.md_amber_600);
}
I can see you have used setOffScreenPageLimit as 1. It means you are loading only 1 extra screen at a time using viewPager, when actually you want to load nothing. It is not possible to set 0 value for setOffScreenPageLimit this method, actually you can set it but it will not work.
So, it is not possible to achieve this using view pager. If you still want to perform such a functionality, you can use FrameLayout and switch between the fragments based on tab selection.
Below is the tab selection code sample:
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
switchToTab(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});

Change tab index of fragments with tabs programmatically

I'm getting a null pointer exception when trying to switch tabs programmatically of a tablayout inside a fragment,
So I have my main activity that has a tab layout (4 tabs) each tab has a view pager holding a fragment, and each of these fragments has a tab layout (x amount of tabs) with a view pager holding a fragment,
i can switch the tabs of my main activity tab layout from any fragment like this
TabLayout tabLayout = MainActivity.tabLayout;
TabLayout.Tab tab = tabLayout.getTabAt(2);
tab.select();
but if i try to change the tabs of one of the fragments in the same way i get a null pointer
TabLayout tabLayout2 = tabFragOne.tabLayout;
TabLayout.Tab tab2 = tabLayout2.getTabAt(2);
tab2.select();
it only happens if I click the button in question when the app first opens, which suggests that the reason for it is that the fragment hasn't been attached or created yet,
for instance if i scroll across to the fragments tab i want to switch to, and then go back to the main activity and press the button in question it will work.
does anyone know the best way to fix this?
Ok ive found half the crux to this question is actually that im using a view pager adapter, a question here sheds a lot of light on my issue
The correct way to set selected Tab, we should set selected index from Pager instead.
final ViewPager pager = (ViewPager) findViewById(R.id.pager);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(pager);
pager.setCurrentItem(0);//selected position
Here is my layout design in xml
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="#ffffff"
android:background="#color/al_white"
android:elevation="0dp" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
app:tabTextColor="#494a43"
app:tabSelectedTextColor="#494a43"
app:tabIndicatorColor="#494a43"
app:tabIndicatorHeight="2dp"
app:tabMode="fixed"
app:tabGravity="fill" />
</android.support.design.widget.AppBarLayout>
TabLayout tabhost = (TabLayout) getActivity().findViewById(R.id.tabLayout);
tabhost.getTabAt(2).select();
I use this inside my fragment's create function... and it works perfectly
R.id.tabLayout is the tablayout id in your main activity layout.
you can use the setCurrentItem(Postion) in viewpager
example :
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
// tabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(4);
Simple example to automatically scroll from the last page to the first. Note: I added a dummy fragment at the first and last position.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (position == 0) {
viewPager.setCurrentItem(viewPagerAdapter.getCount() - 2);
} else if (position == viewPagerAdapter.getCount() - 1) {
viewPager.setCurrentItem(1);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
Using view pager, Its working simple and fine
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs;
String mode;
AllDeals deals;
MyDeals myDeals; those are my fragments
public ViewPagerAdapter(FragmentManager fm, int mNumbOfTabsumb, String moe) {
super(fm);
this.NumbOfTabs = mNumbOfTabsumb;
mode=moe;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
if(mode.equals("Deals")){
deals=new AllDeals();
return deals;
}
break;
case 1:
if(mode.equals("Deals")){
myDeals=new MyDeals();
return myDeals;
}
break;
default:
break;
}
return null;
}
#Override
public int getCount() {
return NumbOfTabs;
}
}
add this lines into ur activity
containerViewone.setVisibility(View.VISIBLE);
tabLayout.addTab(tabLayout.newTab().setText(getResources().getString(R.string.title_all_deals)));
tabLayout.addTab(tabLayout.newTab().setText(getResources().getString(R.string.title_my_deals)));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabTextColors(getResources().getColor(R.color.tabunselect), getResources().getColor(R.color.black));
viewpagerad = new ViewPagerAdapter(getSupportFragmentManager(), Numboftabs, "Deals");
pager.setAdapter(viewpagerad);
pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
Try this:
TabLayout tablayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //your activity layout
tabLayout =(TabLayout)findViewById(R.id.tablayout); //your tab layout id
tabLayout.getTabAt(0).select(); //your tab index;
}
In Kotlin:
With TabLayout and ViewPager2 that works for me:
binding.tablayout.getTabAt(1)!!.select()

Android: Updating tab content

I am new to Android development. I have a ViewPager which holds TabLayout (that has fixed number of tabs). The ViewPager has SectionPagerAdapter (that has a fragment corresponding to tabs).
Now, I want to update tab content when user selects the tab and as it becomes visible (or when user wants to refresh the content).
But I am not sure which is correct way I can do this.
So far till now I found two solutions:
1) Add listener to TabLayout:
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
#Override
public void onTabSelected(TabLayout.Tab tab)
{
mViewPager.setCurrentItem(tab.getPosition());
// Update tab containts here
}
#Override
public void onTabUnselected(TabLayout.Tab tab)
{
}
#Override
public void onTabReselected(TabLayout.Tab tab)
{
}
});
2) Use ViewPager.OnPageChangeListener to get callbacks for when a page fragment (inside Tab) becomes visible:
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener()
{
#Override
public void onPageSelected(int position)
{
// Update tab containts here
}
});
Can someone expert in this please advice me?
The way a viewpager adapter works (with tabs) is that once you add your fragments to the viewpager, then you basically need to add content to your fragments and let the adapter manage which fragment is visible when a given tab is selected.
So, by simply using : OnTabSelectedListenerinterface on your tabLayout, all you need to do is `setCurrentItem(tab.getPosition()); on your viewPager reference (from your layout).
You can have a method like this to add fragments to your viewPagerAdapter:
private void setupViewPager(ViewPager viewPager){
//then create an instance of your ViewPagerAdapter class here
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
//then add fragments for each TAB here
//by calling a method inside your Adapter like this
adapter.addFrag(new FragmentOne(), "TITLE HERE");
adapter.addFrag(new FragmentTwo(), "TITLE TWO");
//Now set your adapter here
viewPager.setAdapter(adapter);
}
Now in your fragments, you can show different content accordingly.
I hope this helps!

How can make Swip ActionBar-Tabs inside a fragment

I have a FragmentActivity and some fragment in my app.
i need to have Swip ActionBar-Tabs Just inside one fragment , but when i use ActionBar and ViewPager in my project to make Swip ActionBar Tab , make ActionBar in all of fragment No just in one,
hove i can make ActionBar just inside one fragment that not shown in other fragment?
actionabar = getActionBar();
actionabar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
viewpager = (ViewPager) findViewById(R.id.pager);
FragmentManager fm = getSupportFragmentManager();
/** Defining a listener for pageChange */
ViewPager.SimpleOnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
actionabar.setSelectedNavigationItem(position);
}
};
/** Setting the pageChange listner to the viewPager */
viewpager.setOnPageChangeListener(pageChangeListener);
/** Creating an instance of FragmentPagerAdapter */
MyFragmentPagerAdapter fragmentPagerAdapter = new MyFragmentPagerAdapter(fm);
viewpager.setAdapter(fragmentPagerAdapter);
actionabar.setDisplayShowTitleEnabled(true);
Tab tab = actionabar.newTab().setText("My Friends").setTabListener(tabListener);
actionabar.addTab(tab);
tab = actionabar.newTab().setText("Android Version").setTabListener(tabListener);
actionabar.addTab(tab);
tab = actionabar.newTab().setText("Android Phones").setTabListener(tabListener);
actionabar.addTab(tab);
Use TabHost (http://developer.android.com/reference/android/support/v4/app/FragmentTabHost.html) instead of ActionBar navigation mode.

Updating fragments/views in viewpager with fragmentStatePagerAdapter

Need some help with my problem of updating pages while using viewpager. I am using a simple viewpager with FragmentStatePagerAdapter. All I want to do is get access to the current fragment/view so as I can update some textviews in my fragment/view. I searched around in the forum and came to know few things
- One of the ways to handle this is by setting tag in instantiateItem() call back of the adapter and retreive the view by findViewbyTag. I could not understand how to implement this and I am also not sure if that will work for FragmentStatePagerAdapter.
- I explored other options as suggested in various forums, but cannot make them work.
My code is very much same as in a android http://developer.android.com/training/animation/screen-slide.html. Basic components are the same (Fragment activity xml with some display components including a textview, viewpager xml with just a view pager in it, a Fragment class and the main FragmentActivity class). in my FragmentActivity class I have added a pageChangelistener to my viewpager so as I can do my textview changes during onPageSelected().
Any help is is appreciated.
Adding the code for reference.
Public class myActivity extends FragmentActivity
//Variable declarations
protected void onCreate(Bundle savedInstanceState) {
ViewPager mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
View CurrView;
OnPageChangeListener pageChangelistener = new OnPageChangeListener() {
#Override
public void onPageSelected(int pageSelected) {
doTextViewChnges();//access the text view and update it based on pageSelected
---THIS IS WHERE I AM STUCK IN TRYING TO GET THE TEXTVIEW IN MY CURRENT FRAGMWNT/VIEW-------
}
mPager.setOnPageChangeListener(pageChangelistener);
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return ScreenSlidePageFragment.create(position, <other parameters I want to pass>);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
in your OnPageChangeListener:
OnPageChangeListener pageChangelistener = new OnPageChangeListener() {
#Override
public void onPageSelected(int pageSelected) {
ScreenSlidePageFragment currentFragment = (ScreenSlidePageFragment) mPagerAdapter.getItem(pageSelected)
doTextViewChnges();//access the text view and update it based on pageSelected
---THIS IS WHERE I AM STUCK IN TRYING TO GET THE TEXTVIEW IN MY CURRENT FRAGMWNT/VIEW-------
}
i assume you want to access your fragments from your activity and update the views.Fragments are parts of activities and their views can be accessed by them. Fragments are created dynamically in viewadapters and there is no straight forward and easy way to Tag them. You may simply access a fragment by its index number.first one is 0 second one is 1 and so on...
//access your fragment(in your case your first fragment)
//this part should be inside your doTextViewChnges()
Fragment fragment = (Fragment ) adapterViewPager
.getFragment(0);
if (fragment != null) {
//call a public method inside your fragment to update your text view
fragment .updateYourTextView();
}
Edit: inside your fragment create the following method and update your textview from there.
void updateYourTextView() {
yourTextView.setText("yourtext");
}

Categories

Resources