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 :)
Related
I have created a navigation drawer and added fragments to it.Now I want to insert tab layout into one of the fragment.I have added tab layout into one fragment containing 2 tabs,but I dont know how to add contents into each of these tabs separately.Please help me
enter image description here
I need my tabs to look like in the image..Each tab having its own fragment
I don't know how to add contents into each of these tabs separately
Answer : Same as you add TabLayout in activity.
fragment_parent.xml is parent fragment having TabLayout.
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".NewFragment">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
app:tabTextAppearance="?android:attr/textAppearanceMedium"
app:tabTextColor="#ffffff"
android:layout_height="?android:actionBarSize"
app:tabMode="fixed"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:background="#android:color/white"/>
FragmentParent.java
public class NewFragment extends Fragment {
private RecyclerView mRecyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_parent, container, false);
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.addTab(tabLayout.newTab().setText("A"));
tabLayout.addTab(tabLayout.newTab().setText("B"));
tabLayout.addTab(tabLayout.newTab().setText("C"));
final ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(new PagerAdapter(getFragmentManager(), tabLayout.getTabCount()));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
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;
}
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:
return new FragmentChild();
case 1:
return new FragmentChild();
case 2:
return new FragmentChild();
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
}
fragment_child.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
FragmentChild.java
public class FragmentChild extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_child, container, false);
}
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 have an activity containing a TabLayout with tabMode set to 'scrollable':
<android.support.design.widget.CoordinatorLayout 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.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar" app:layout_scrollFlags="scroll|enterAlways"
android:layout_width="match_parent"
android:layout_height="?android:actionBarSize"
android:background="#color/primary"
android:titleTextColor="#color/white">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="?android:actionBarSize"
android:layout_below="#+id/toolbar" android:layout_gravity="bottom" app:tabMode="scrollable"
app:tabGravity="fill" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
Most of the time, the TabLayout displays correctly and shows the entire title text for each tab, like this:
Sometimes, however, it displays only the first two characters from the title, like this:
During the activity's creation, I am calling:
setSupportActionBar(getToolbar());
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
Within my fragment, which is being rendered in my activity, I am initializing the TabLayout as follows:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_pager, null);
viewPager = (ViewPager) view.findViewById(R.id.view_pager);
setupViewPager(viewPager);
TabLayout tabs = (TabLayout)getActivity().findViewById(R.id.tabs);
tabs.removeAllTabs();
tabs.setVisibility(View.VISIBLE);
tabs.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabs));
return view;
}
private void setupViewPager(ViewPager viewPager) {
adapter = new PeopleFragmentAdapter(getChildFragmentManager());
viewPager.setAdapter(adapter);
}
The FragmentAdapter code looks like this:
public class PeopleFragmentAdapter extends FragmentPagerAdapter {
public PeopleFragmentAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return PeopleFragment.newInstance(position);
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Nearby";
case 1:
return "Online";
default:
return "Following";
}
}
}
The PeopleFragment which is hosted inside the first fragment, created an options menu from an XML file:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().getInt(ARG_SECTION_NUMBER, 0) < 2)
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_people, menu);
}
The reason the TabLayout is in the activity's layout rather than the first fragment, is because it is being re-used by other fragments which are accessible via a BottomBar.
Strangely, and possibly not relevant, when I took a screenshot of the device while it was exhibiting the issue, the height was substantially greater than usual (as you can see in the screenshot above).
What might be causing the TabLayout to truncate the the titles? Is the extra tall screenshot being created somehow related?
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());
I have a main activity, which hosts a fragment, which in turn hosts a TabLayout (with a ViewPager). The tab bar is shown, baut the tabs themselves are not shown.
Here is my code in the main activity for displaying the host fragment:
Fragment fragment = new BMITabsFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(Constants.BMI_TABS_FRAGMENT).commit();
Here is my the Fragment which hosts the TabLayout, which is BMITabsFragment (s.a.):
public class BMITabsFragment extends Fragment {
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
viewPager.setAdapter(new BMIFragmentPagerAdapter(getActivity().getSupportFragmentManager(),
getActivity()));
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) view.findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_bmitabs, container, false);
return view;
}
...
}
This is my FragmentPagerAdapter:
public class BMIFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 2;
private FragmentManager fragmentManager;
private Context context;
public BMIFragmentPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
this.fragmentManager = fm;
}
public BMIFragmentPagerAdapter(FragmentManager fm) {
super(fm);
fragmentManager = fm;
}
#Override
public CharSequence getPageTitle(int position) {
String[] pageTitles = context.getResources().getStringArray(R.array.page_titles_array);
return pageTitles[position];
}
#Override
public Fragment getItem(int position) {
SharedPreferences prefs = context.getSharedPreferences(Constants.SHARED_PREFS_FILE, 0);
long patientId = prefs.getLong(Constants.SELECTED_PATIENT_ID, 1);
Fragment fragment = null;
switch (position){
case 0:
return BMITabelleFragment.newInstance(patientId);
case 1:
return BMIChartFragment.newInstance(patientId);
default:
return BMITabelleFragment.newInstance(patientId);
}
}
#Override
public int getCount() {
return PAGE_COUNT;
}
}
And this is the fragment_bmitabs.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#android:color/white" />
</LinearLayout>
My code is based on the Google Android Guide at https://github.com/codepath/android_guides/wiki/Google-Play-Style-Tabs-using-TabLayout
What I am missing here?
Note: I am using AppCompatActivity and the support libraries v4 & v7 and the com:android:support:design library
This fixed it for me:
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
https://code.google.com/p/android/issues/detail?id=180462
Set tab icons after setupWithViewPager()
private void setTabs {
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
}
like #Nathaniel Ford said,this should a bug, I change to use design library 23.0.1。google fixed it,so change build.gradle to compile 'com.android.support:design:23.0.1'. ps:you also must change your compileSdkVersionto 23
None of the other answers worked for me, I tried all of them
However, this one did: TabLayout not showing tabs after adding navigation bar
According to that answer, you have to enclose your TabLayout in a AppBarLayout. Why? Who knows. But at least it works.
Example Code (taken from that post):
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:id="#+id/appBarLayout2">
<android.support.design.widget.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tabLayout2"
app:tabMode="fixed"
app:tabGravity="fill"
></android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:id="#+id/viewPager2"
android:layout_below="#+id/appBarLayout2">
</android.support.v4.view.ViewPager>
If you are using android:tabPadding attribute in Tablayout of xml file,remove it.
You can use FragmentStatePagerAdapter instead of FragmentPagerAdapter.
It may help you.
If someone, in future, works with TabLayout along with ViewPager2 and faces same issue. Just add .attach(); at end of new TabLayoutMediator().
new TabLayoutMediator(tabLayoutRef, viewPager2Ref, (tab, position) -> tab.setText("Tab No. "+position)).attach();