Reputation: 953
I am using Fragment
class and TabLayout
with ViewPager
to implement swipe tabs.
I have 3 java class:
(OneFragment extends Fragment, TwoFragment extends Fragment, ThreeFragment extends Fragment and MainActivity extends AppCompatActivity)
Also I have 4 different xml files for all these class. In fact, I designed my code according to this tutorial
Now I want to listen when user switch between tabs. For example When the user goes 1st tab to 2nd tab, I want this to execute:
Toast t = Toast.makeText(getActivity(),"You are exit from 1st tab", Toast.LENGTH_LONG);
t.show();
Or when the user goes to 1st or 3rd tab from 2, this should be executed:
Toast t = Toast.makeText(getActivity(),"You are exit from 2nd tab", Toast.LENGTH_LONG);
t.show();
It is interesting that I couldn't any answer for TabLayout
, although there are tens of answers for Tabhost
.
How can I design my code to understand "which tab is changing, What is previous tab?" in TabLayout
?
Note: I used, tried to override onDestroyView()
, onDestroy()
and onHiddenChanged()
but I couldn't solve my problem. Only onDestroy()
worked but it is working when the user exits the application as well.
Upvotes: 2
Views: 2656
Reputation: 2065
You will need to implement the TabLayout.OnTabSelectedListener
interface for that.
Use addOnTabSelectedListener
and removeOnTabSelectedListener
methods to do so. Note that setOnTabSelectedListener
is now deprecated.
Upvotes: 3