android.support.design.widget.TabLayout not working properly with ViewPager
If I set tabLayout.setupWithViewPager(viewPager); then tablayout view not showing please find attached screen shots.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:fitsSystemWindows="false"
android:orientation="vertical"
tools:context=".home.HomeActivity"
tools:showIn="#layout/activity_home">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
Fragment Code :
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab_layout); tabLayout.addTab(tabLayout.newTab().setText(getActivity().getResources().getText(R.string.feeds))); tabLayout.addTab(tabLayout.newTab().setText(getActivity().getResources().getText(R.string.following))); tabLayout.addTab(tabLayout.newTab().setText(getActivity().getResources().getText(R.string.you)));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) view.findViewById(R.id.pager);
final PageAdapter adapter = new PageAdapter(getChildFragmentManager(), 3);
viewPager.setOffscreenPageLimit(3);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
When remove "tabLayout.setupWithViewPager(viewPager);" the view is working fine. But I need navigate respective fragment when click on respective tab.
In my case I solved this by replacing,
tabLayout.setupWithViewPager(viewPager);
By,
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) {
}
});
I hope this will help you out.
Incase if you are using tabLayout inside fragment try this answer
Possible mistake
you need to pass getChildFragmentManager() to FragmentPagerAdapter
not getSupportFragmentManager() or getFragmentManager()
//wrong one
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
//correct one
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
ViewPagerAdapter is FragmentPagerAdapter
public class ViewPagerAdapter extends FragmentPagerAdapter {
}
Short version of solution (Naveen Kumar M):
viewPager.addOnPageChangeListener(
new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
try this
add this to viewpager.
app:layout_behavior="#string/appbar_scrolling_view_behavior"
Also keep to parent as Coordinator layout then only scrolling will work fine
Refer here:http://coderzpassion.com/working-appbarlayout-like-whatsapp/
Check the getCount().
DON'T RETURN IT TO NULL! RETURN TO blankFragment.
package my.package;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class tabPagers extends FragmentStatePagerAdapter {
String[] titles = new String[]{"Home", "Campus", "Course"};
public tabPagers(FragmentManager fm) {
super(fm);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
#Override
public Fragment getItem(int position) {
BlankFragment blankFragment = new BlankFragment();
Blank2Fragment blank2Fragment = new Blank2Fragment();
Blank3Fragment blank3Fragment = new Blank3Fragment();
switch (position) {
case 0:
return blankFragment;
case 1:
return blank2Fragment;
case 3:
return blank3Fragment;
}
return blankFragment; //This one is important
}
#Override
public int getCount() {
return titles.length; //This one is important too
}
}
https://developer.android.com/reference/com/google/android/material/tabs/TabLayout#viewpager-integration
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top" />
</androidx.viewpager.widget.ViewPager>
Related
I'm trying to show fragments in viewPager with tabsLayout but the viewPager shows nothing. However, the tabs have been added to the view.
I have also put some logs in the fragments just to make sure that they're created and it's showing the logs - nothing wrong with the fragments.
the layout that contains the tabs and viewPager:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:tabIndicatorColor="#color/colorAccent"
app:tabMode="fixed"
app:tabSelectedTextColor="#color/colorAccent"
app:tabTextAppearance="#style/customTabsStyle"
app:tabTextColor="#000" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Then in MainActivity I have this code:
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.promotions)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.all_stores)));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final HomeTabsAdapter tabsAdapter = new
HomeTabsAdapter(MainActivity.this,getSupportFragmentManager(),
tabLayout.getTabCount());
viewPager.setAdapter(tabsAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
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) {
}
});
And this is part of HomeTabsAdapter:
public HomeTabsAdapter(Context c, FragmentManager fm, int totalTabs) {
super(fm);
context = c;
this.totalTabs = totalTabs;
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position) {
case 1:
return getAllStoresFragment();
default:
return getPromotionsFragment();
}
Note: Both fragments are of the same type but i'm showing different stuff based on the Arguments. (I'm using the getInstance(..) way to handle this using Bundle and Arguments).
What changes to this code could solve the issue?
The position starts at 0.
#NonNull
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return getAllStoresFragment();
default:
return getPromotionsFragment();
}
I have a activity that contain 2 fragments and both the fragments containing a recyclerview.
I need to implement a swipe gesture (when i swipe from one side to another the fragments need to be changed).
Previously i have added swipe gesture, but when i swipe the recycler view will scroll instead of change of fragments.
Can you help in implementing this..
Thanks
Use TabLayout with ViewPager. Create two tabs for two fragments in the activity .
http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/
just use Android TabLayout with ViewPager and your problem will be solved :)
This is how you can do it:
public class YourActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentOne(), "Fragment One");
adapter.addFragment(new FragmentTwo(), "Fragment Two");
viewPager.setAdapter(adapter);
}
private class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
ViewPagerAdapter(FragmentManager fragmentManager) {super(fragmentManager);}
#Override
public Fragment getItem(int position) {return fragmentList.get(position);}
#Override
public int getCount() {
return fragmentList.size();
}
void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
}
And this is the .XML file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".YourActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="8dp"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.design.widget.CoordinatorLayout>
Hope it helps!
Simply use Tablayout and ViewPager
Here the code :-
public class DispatchOrderTab extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2 ;
android.support.v4.app.FragmentManager mFragmentManager;
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
getActivity().setTitle("Order");
View x = inflater.inflate(R.layout.activity_dispatch_order_tab,null);
tabLayout = (TabLayout) x.findViewById(R.id.sliding_tabs_dispatchtoken);
viewPager = (ViewPager) x.findViewById(R.id.viewpagerdispatchtoken);
viewPager. setOffscreenPageLimit(2);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
return x;
}
class MyAdapter extends FragmentPagerAdapter {
Order order;
Home home;
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position)
{
switch (position){
//Here u can put your fragment files for swipe
case 0 : return new Dispatchorder();
case 1 : return new DispatchOrderTokenComplete();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
//Here you can put the name of tabs.
return "Pending Order";
case 1 :
return "Complete Order";
}
return null;
}
}
}
Here the xml :-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="com.Weal.sachin.omcom.TabFragment"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs_dispatchtoken"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#11977c"
app:tabTextColor="#d2cece"
app:tabSelectedTextColor="#fff"
/>
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/viewpagerdispatchtoken"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white">
android:background="#color/white">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/framelayout1"></FrameLayout>
</android.support.v4.view.ViewPager>
</android.support.design.widget.CoordinatorLayout>
</LinearLayout>
Hope this will help you... :)
I want to create customized swipeable tabs in my android application project as I have provided in the
picture here
.
Since link only answers are not allowed in the SO, adding some kind of steps to do.
Step 1 :
Define three different set of Fragment Classes that will be used for each tabs. [ Android recommends to use fragments instead of Activity ]
Step 2 :
Define a Pager adapter that will help you to load the above three fragments under each tabs.
Step 3 :
In you main activity define the tablayout, and set the above adapter as shown in the tutorial link.
Kindly refer the below tutorial, that is very basic and help you achieve what you needed.
http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/
Above link, only guides you to implement the swipe-able views. If you need to implement the exact design like the image you posted needs some work in your styles xml or try with drawable images here.
One more useful link
Let me know for queries.
EDIT
I'm also refering to the same thing what #kush mentioned.
Try this..
As I tried.. you can do well..
activity_main.xml
<RelativeLayout
android:id="#+id/main_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
</RelativeLayout>
In your MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...........................
...........................
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
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) {
}
});
}
add PagerAdapter.java
package com.truiton.designsupporttabs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
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:
TabFragment1 tab1 = new TabFragment1();
return tab1;
case 1:
TabFragment2 tab2 = new TabFragment2();
return tab2;
case 2:
TabFragment3 tab3 = new TabFragment3();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
Reference...
http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/
I found a way to make similar tab layout using pageadapter. Below is the code for the same.
MainActivity code:
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Locate the viewpager in activity_main.xml
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Set the ViewPagerAdapter into ViewPager
viewPager.setAdapter(new PagerAdapter(getSupportFragmentManager()));
}
}
MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.PagerTabStrip
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:textColor="#000000" />
</android.support.v4.view.ViewPager>
PageAdapter.java
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class PagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3;
// Tab Titles
private String tabtitles[] = new String[] { "PLAYLIST", "SONGS", "ALBUMS" };
Context context;
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
// Open FragmentTab1.java
case 0:
SongsList fragmenttab1 = new SongsList();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
SecondFragment fragmenttab2 = new SecondFragment();
return fragmenttab2;
// Open FragmentTab3.java
case 2:
ThirdFragment fragmenttab3 = new ThirdFragment();
return fragmenttab3;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
}
You can create n fragments in your project. Here is the example fragment code.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SecondFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.fragment_second, container, false);
return view;
}
}
and its XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/Fragment2" />
</RelativeLayout>
Add this RESOURCE values to remove the action bar,title bar in layout in styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
</resources>
I have created an android activity that contains three tabs using tablayout and pager adapter. every tab has its Java file and (its layout in res/Layout folder).
the first tap has no problem while the problem appears in the second and the 3rd tab.
there is a difference between the layout xml design in android studio and when it is inflated on the emulator or real device.
the objects aren't in its correct positions and shifted horizontally and vertically! what is the problem causing this?
Android Studio Pic: (Spinners are in the correct position)
Emulator PIC: (Spinners are in incorrect positions)
Tab 3 Layout Design Example:
<RelativeLayout>
<ScrollView>
<RelativeLayout>
<TextView>
<TextView>
<Spinner>
<Spinner>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
there are so many textviews and everyone has a spinner in front of it. and the problem appears in the spinners position, they are shifted up.
Tab 3 Java file:
public class DCO_New_Report extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.dco_new_report, container, false);
}
}
Main Activity Java:
public class DCODatabase extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dcodatabase);
Toolbar toolbar = (Toolbar) findViewById(R.id.DCODatabaseToolbar);
setSupportActionBar(toolbar);
assert toolbar != null;
toolbar.setLogo(R.drawable.dco1);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab);
assert tabLayout != null;
tabLayout.addTab(tabLayout.newTab().setText("General Reports"));
tabLayout.addTab(tabLayout.newTab().setText("Report Display"));
tabLayout.addTab(tabLayout.newTab().setText("New Report"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
assert viewPager != null;
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) {
}
});
}
}
Main Activity XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="esmviewer.myandroid.com.esmviewer.DCODatabase">
<android.support.v7.widget.Toolbar
android:id="#+id/DCODatabaseToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/DCODatabaseToolbar"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab"/>
</RelativeLayout>
Pager Adapter Java File:
public class PagerAdapter extends FragmentStatePagerAdapter{
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int mNumOfTabs) {
super(fm);
this.mNumOfTabs = mNumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
DCOGeneralReports tab1 = new DCOGeneralReports();
return tab1;
case 1:
DCOReportDisplay tab2 = new DCOReportDisplay();
return tab2;
case 2:
DCO_New_Report tab3 = new DCO_New_Report();
return tab3;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
For each row, make a LinearLayout with orientation set to horizontal.
Then add a TextView and a Spinner to it with proper weights and it should work.
Hope this hepls :)
This question already has an answer here:
Lifecycle of a replaced ViewPager and BackStack?
(1 answer)
Closed 7 years ago.
I'm using a TabLayout in one of my fragments with a viewPager to switch between two fragments below the tabs.
When I click the FAB inside one of the lower fragments, I load a new fragment (for input).
However- when I press the BACK button, the TabLayout shows up but WITHOUT either of the lower fragments (represented by the pages).
So what am I doing wrong?
and is there a better way to be swapping fragments?
and is there a way to press the back button and get back to the viewPager Page that was showing?
Fragment with TabLayout: CustomTemplatesFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_custom_templates, container, false);
final TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText(R.string.macro_tab));
tabLayout.addTab(tabLayout.newTab().setText(R.string.lifestyle_tab));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) view.findViewById(R.id.pager);
final CustomTemplatesPagerAdapter adapter = new CustomTemplatesPagerAdapter
(getFragmentManager(), 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) {
}
});
return view;
}
Pager Adapter: CustomTemplatePagerAdapter
public class CustomTemplatesPagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public CustomTemplatesPagerAdapter(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
CustomMacroFragment tab1 = new CustomMacroFragment();
return tab1;
case 1:
CustomLifestyleFragment tab2 = new CustomLifestyleFragment();
return tab2;
default:
return null;
}
}
Lower Fragment with FAB: CustomMacroFragment
private void onFABClicked() {
Fragment fragment = null;
Class fragmentClass = MacroTemplateDetailFragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fm = getActivity().getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.flContent, fragment);
ft.addToBackStack(null);
ft.commit();
}
TabLayout/ViewPager XML
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/customLayout"
tools:context=".CustomTemplatesFragment">
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<!--android:minHeight="?attr/actionBarSize"-->
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
Fragment with FAB XML
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/macroCoordinator"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CustomMacroFragment">
<!-- using RecyclerView because of
https://guides.codepath.com/android/Floating-Action-Buttons -->
<android.support.v7.widget.RecyclerView
android:id="#+id/rvMacrolist"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
<TextView
android:id="#+id/emptyView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal|center_vertical"
android:visibility="gone"
android:text="Please add a Macronutrient Template"/>
<!--https://guides.codepath.com/android/Floating-Action-Buttons-->
<android.support.design.widget.FloatingActionButton
android:id="#+id/macroListFAB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="#dimen/activity_margin"
android:src="#drawable/ic_plus"
app:layout_anchor="#id/rvMacrolist"
app:layout_anchorGravity="bottom|right|end"
app:layout_behavior=".utilities.behavior.ScrollAwareFABBehavior"/>
I believe found the answer here: Lifecycle of a replaced ViewPager and BackStack?
Works for initial testing. Need to replace getFragmentManager() with getChildFragment Manager at the adapter
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());