How Can I display Tabs on A Fragment? - android

My navigation drawer is built using fragments. I want to display tabs on one of the fragments. So far, nothing is showing up. Home fragment is a fragment that is accessed upon clicking home icon on the navigation drawer. I am trying to create two tabs under home fragment without any success. I have already created a class for each tab. The classes inflate their respective layouts.
Home Fragment:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState){
View view = inflater.inflate(R.layout.daily_data_fragment, null);
//Adding toolbar to the activity
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
//Initializing the tablayout
tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
//Adding the tabs using addTab() method
tabLayout.addTab(tabLayout.newTab().setText("ADD DATA"));
tabLayout.addTab(tabLayout.newTab().setText("VIEW ARCHIVE"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//Initializing viewPager
viewPager = (ViewPager) view.findViewById(R.id.pager);
//Creating our pager adapter
DailyDataPageAdapter adapter = new DailyDataPageAdapter(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
//Adding adapter to pager
viewPager.setAdapter(adapter);
//Adding onTabSelectedListener to swipe views
tabLayout.setOnTabSelectedListener(this);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return view;
}
Adapter Class:
public class DailyDataPageAdapter extends FragmentStatePagerAdapter {
int tabCount;
public DailyDataPageAdapter(FragmentManager fm, int tabCount){
super(fm);
this.tabCount = tabCount;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
AddData addData = new AddData();
return addData;
case 1:
ViewArchive viewArchive = new ViewArchive();
return viewArchive;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
Layout:
<LinearLayout
android:id="#+id/main_layout"
android:orientation="vertical"
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=".home_activity">
<!-- our toolbar -->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:visibility="visible"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<!-- our tablayout to display tabs -->
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorgray"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:visibility="visible" />
<!-- View pager to swipe views -->
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:visibility="visible" />
</LinearLayout>

You can do like this.
public class HomeFragment extends Fragment {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
// Fragment List
private final List<Fragment> mFragmentList = new ArrayList<>();
// Title List
private final List<String> mFragmentTitleList = new ArrayList<>();
private ViewPagerAdapter adapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.daily_data_fragment,container,false);
// init view
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
viewPager = (ViewPager) view.findViewById(R.id.pager);
tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// add title to the list
mFragmentTitleList.add("one");
mFragmentTitleList.add("two");
mFragmentTitleList.add("three");
// add fragment to the list
mFragmentList.add(new OneFragment());
mFragmentList.add(new TwoFragment());
mFragmentList.add(new ThreeFragment());
setupViewPager(viewPager);
tabLayout.setupWithViewPager(viewPager);
// Tab ViewPager setting
viewPager.setOffscreenPageLimit(mFragmentList.size());
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabsFromPagerAdapter(adapter);
return view;
}
private void setupViewPager(ViewPager viewPager) {
adapter = new ViewPagerAdapter(getChildFragmentManager(), mFragmentList, mFragmentTitleList);
viewPager.setAdapter(adapter);
}
/**
* ViewPagerAdapter setting
*/
class ViewPagerAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragmentList = new ArrayList<>();
private List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragments, List<String> titleLists) {
super(fm);
this.mFragmentList = fragments;
this.mFragmentTitleList = titleLists;
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList == null ? 0 : mFragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}

Related

How to add ViewPager in Fragment Class?

I am trying to add View Pager in Fragment Class. I have tried all stuff.
public class MessageFragment extends android.support.v4.app.Fragment{
private ViewPager viewPager;
private TabLayout tabLayout;
public static MessageFragment newInstance() {
MessageFragment fragment = new MessageFragment();
Log.d("Click", "newInstance: ");
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_message, container, false);
ViewPager viewPager=(ViewPager)view.findViewById(R.id.viewpager);
if(viewPager!=null)
{
setUpViewPager(viewPager);
}
TabLayout tabLayout = (TabLayout)view. findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabTextColors(getResources().getColorStateList(R.color.colorToolbar));
return view;
}
private void setUpViewPager(ViewPager viewPager)
{
Adapter adapter=new Adapter(getActivity().getSupportFragmentManager());
adapter.addFragment(new TabTaskFragment(),"Tasks");
adapter.addFragment(new TabChatFragment(),"Chat");
viewPager.setAdapter(adapter);
}
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public Adapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
}
Here is my xml file, I have added all viewpager code over here
please find
XML FILE:
<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:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"
app:layout_scrollFlags="scroll|enterAlways|snap"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white"
app:tabIndicatorColor="#color/colorToolbar"
app:tabTextAppearance="#android:style/TextAppearance.Widget.TabWidget"
app:tabTextColor="#color/colorToolbar" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
How can I add?
I am not able to fix it.
Tabs will show 1st time, but when the user clicks on any bottom tab than tabs description gone and its show blank screens.
I have tried all stuffs disappointed at last.
Your class file should like this
public class ViewPagerFragment extends Fragment {
ViewPager viewPager;
PagerAdapter mPagerAdapter;
TabLayout tabLayout;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.myLayout, null);
viewPager = (ViewPager) view.findViewById(R.id.transactions_recharge);
mPagerAdapter = new ViewPagerAdapter(getChildFragmentManager(), 7);
viewPager.setAdapter(mPagerAdapter);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return view;
}
class ViewPagerAdapter extends FragmentPagerAdapter {
int pageCount = 0;
String titles[] = {"One", "Two", "Three"};
ViewPagerAdapter(FragmentManager manager, int _pageCount) {
super(manager);
pageCount = _pageCount;
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
//load fragment one
return new FragmentOne();
} else if (position == 1) {
//load fragment two
} else if (position == 2) {
//load fragment three
}
}
#Override
public int getCount() {
return pageCount;
}
#Override
public CharSequence getPageTitle(int position) {
return titles[position];
}
}
}
And your XML should me like this.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:id="#+id/content_layout"
android:layout_height="match_parent"
android:background="#color/primary">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicatorColor="#color/white"
app:tabIndicatorHeight="2dp"
app:tabMode="scrollable" />
<android.support.v4.view.ViewPager
android:id="#+id/transactions_recharge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabs"
android:background="#android:color/transparent">
</android.support.v4.view.ViewPager>
</RelativeLayout>

OnBackpressed get empty view on tablayout

I am stuck in solving this problem. I have set tabs in fragment using TabLayout and ViewPager. The problem is when i move to next fragment and then i press back button i get empty tabs view.
Here I am attaching my code:
home.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabIndicatorColor="#android:color/white"
app:tabIndicatorHeight="4dp" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent" />
</LinearLayout>`
home.java(fragment)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home, container, false);
((Drawer) getActivity()).setActionBarTitle("Home");
Toast.makeText(getActivity(), "entry count" + getActivity().getSupportFragmentManager().getBackStackEntryCount(), Toast.LENGTH_SHORT).show();
tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Products"));
tabLayout.addTab(tabLayout.newTab().setText("Category"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) view.findViewById(R.id.pager);
Pager adapter = new Pager(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
tabLayout.getTabCount());
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(this);
return view;
}
#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) {
}
pager.java (Adapter)
public class Pager extends FragmentStatePagerAdapter {
int tabCount;
public Pager(FragmentManager fm, int tabCount) {
super(fm);
this.tabCount = tabCount;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Product tab1 = new Product();
return tab1;
case 1:
Category tab2 = new Category();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
MainActivity (where I set this tab fragment)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer);
getSupportActionBar().setTitle("Home");
fragment = new home();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.main, fragment);
ft.commit();
I had faced same issue when replacing fragment and that replaced fragment have TabLayout (i.e. Inner Fragments)
After researching about this issue: i found solution
What i does:
replacing
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
to
If your Parent Activity is extending AppCompatActivity , then use
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());
If your Parent Activity is extending Activity than use
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getChildFragmentManager());
write you code in activity
#Override
public void onBackPressed() {
try {
if (getFragmentManager().getBackStackEntryCount() > 1) {
FragmentManager.BackStackEntry first = getFragmentManager().getBackStackEntryAt(0);
getFragmentManager().popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
onNavigationItemSelected(navigationView.getMenu().getItem(0));
} else
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
You do not need to attach PageListeners to tabLayout and tabListeners to ViewPager.
This will take care of this.
tabLayout.setupWithViewPager(viewPager);
Your updated code can be like this. Do tell me if you still face any problem.
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.home, container, false);
((Drawer) getActivity()).setActionBarTitle("Home");
Toast.makeText(getActivity(), "entry count" + getActivity().getSupportFragmentManager().getBackStackEntryCount(), Toast.LENGTH_SHORT).show();
tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Products"));
tabLayout.addTab(tabLayout.newTab().setText("Category"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) view.findViewById(R.id.pager);
Pager adapter = new Pager(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
tabLayout.getTabCount());
//Link tabLayout with ViewPager.
tabLayout.setupWithViewPager(viewPager);
return view;
}
You should not create an Adapter inside a fragment with its activity's FragmentManager. Try to replace
Pager adapter = new Pager(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
with
Pager adapter = new Pager(getChildFragmentManager(), tabLayout.getTabCount());

TabLayout - ViewPager - Fragment

I have a problem with my ViewPager and fragments it contains. I have 2 menus (A and B), my homepage is directly A. When I click on a menu B fragment which contains a TabLayout, which contains a ViewPager himself three fragments (each contains a simple TextView with Lorem ipsum).
The 3 fragments of ViewPager are correct but if I click on the menu A and I click again on the menu B I do not have any content. Nothing on the fragments 1 and 2 against with the 3rd still has the text and if I return to fragment 1 reads income (for nothing against the fragment 2).
Here is my code :
Menu B (FragmentTabLayout)
public class TabLayoutFragment extends Fragment {
private static final String ARG_TEXT = "ARG_TEXT";
private static final String ARG_COLOR = "ARG_COLOR";
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
public TabLayoutFragment() {
// Required empty public constructor
}
public static TabLayoutFragment newInstance(String text, int color) {
Bundle args = new Bundle();
args.putString(ARG_TEXT, text);
args.putInt(ARG_COLOR, color);
TabLayoutFragment tabLayoutFragment = new TabLayoutFragment();
tabLayoutFragment.setArguments(args);
return tabLayoutFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tab_layout, container, false);
toolbar = (Toolbar) view.findViewById(R.id.toolbar);
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
toolbar.setBackgroundColor(getArguments().getInt(ARG_COLOR));
toolbar.setTitle(getArguments().getString(ARG_TEXT));
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) view.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setBackgroundColor(getArguments().getInt(ARG_COLOR));
tabLayout.setSelectedTabIndicatorColor(Color.WHITE);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.tab_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getSupportFragmentManager());
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
//private final List<TabFragment> mFragmentList = new ArrayList<>();
//private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return TabFragment.newInstance("Fragment 2-1");
case 1:
return TabFragment.newInstance("Fragment 2-2");
case 2:
return TabFragment.newInstance("Fragment 2-3");
default:
return TabFragment.newInstance("Fragment Default");
}
}
#Override
public int getCount() {
//return mFragmentList.size();
return 3;
}
}
}
Fragment in ViewPager :
public class TabFragment extends Fragment {
private static final String ARG_TEXT = "ARG_TEXT";
private TextView tv;
public TabFragment() {
// Required empty public constructor
}
public static TabFragment newInstance(String text) {
Bundle args = new Bundle();
args.putString(ARG_TEXT, text);
TabFragment tabFragment= new TabFragment();
tabFragment.setArguments(args);
return tabFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_tab, container, false);
tv = (TextView) view.findViewById(R.id.tv);
return view;
}
}
Layout FragmentTabLayout :
<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:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
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="match_parent"
/>
</android.support.design.widget.CoordinatorLayout>
layout tabFragment :
<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"
android:orientation="vertical"
tools:context="com.application.myapplication.TabFragment">
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
>
<TextView
android:id="#+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/lorem_ipsum"
/>
</android.support.v4.widget.NestedScrollView>
</LinearLayout>
you can extends your ViewPagerAdapter
FragmentStatePagerAdapter
instead of
FragmentPagerAdapter
I have same issue and it works for me.
In my Opinion the better approach is you should try using childFragmentManager for your nested fragments
Here is the simple example:
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getActivity().getChildFragmentManager());
viewPager.setAdapter(adapter);
}
Hopefully it will solve your issue.

TabLayout tabs text not displaying

I am using TabLayout inside a Fragment to display three fixed tabs and the tabs are working but it doesn't show the tab text even after I set the app:tabTextColor attribute in the layout it's still not visible.
NewFragment.java
public class NewFragment extends Fragment {
private RecyclerView mRecyclerView;
private RecyclerView.LayoutManager mLayoutManager;
private RecyclerView.Adapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.new_fragment, container, false);
TabLayout tabLayout = (TabLayout) inflatedView.findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
final ViewPager viewPager = (ViewPager) inflatedView.findViewById(R.id.viewpager);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
viewPager.setAdapter(new PagerAdapter(getFragmentManager(), tabLayout.getTabCount()));
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
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 inflatedView;
}
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 FragmentTab();
case 1:
return new FragmentTab();
case 2:
return new FragmentTab();
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
}
newfragment.xml
<android.support.design.widget.AppBarLayout 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=".NewFragment">
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabTextColor="#ffffff"
app:tabGravity="fill"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"/>
</android.support.design.widget.AppBarLayout>
The problem is you're calling setupWithViewPager() after setting up your tabs with the addTab() calls, effectively overwriting them.
From the documentation of TabLayout regarding setupWithViewPager():
The tabs displayed in this
layout will be populated from the ViewPager adapter's page titles.
If you would like to use your TabLayout with a ViewPager, you should override getPageTitle() in your PagerAdapter (and remove the addTab() calls, they are redundant).
For example:
public class ExamplePagerAdapter extends FragmentStatePagerAdapter {
// tab titles
private String[] tabTitles = new String[]{"Tab1", "Tab2", "Tab3"};
public ExamplePagerAdapter(FragmentManager fm) {
super(fm);
}
// overriding getPageTitle()
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Tab1Fragment();
case 1:
return new Tab2Fragment();
case 2:
return new Tab3Fragment();
default:
throw new RuntimeException("Invalid tab position");
}
}
#Override
public int getCount() {
return tabTitles.length;
}
// ...
}
i added tab text and icon for each tab after calling tabs.setupWithViewPager(viewPager)
viewPager.setAdapter(new MyViewAdapter(getSupportFragmentManager()));
TabLayout tabs=(TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
tabs.getTabAt(0).setIcon(R.drawable.icon1);
tabs.getTabAt(1).setIcon(R.drawable.icon2);
tabs.getTabAt(0).setText(getResources().getText(R.string.tab1));
tabs.getTabAt(1).setText(getResources().getText(R.string.tab2));
I'm using Kotlin and have spent an hour to find the bugs with this code.
var viewPager: ViewPager = view.findViewById(R.id.viewPager)
...
adapter = TabAdapter(fragmentManager!!)
adapter.addFragment(Fragment1(), "Fragment 1")
adapter.addFragment(Fragment2(), "Fragment 2")
viewPager.adapter = adapter
tabLayout.setupWithViewPager(viewpager)
I can compile this with no error, but the tab title is not showing until I realize the viewpager I assigned to the tabLayout is not viewPager (notice the capitalize 'P'). It's not producing error because kotlin will find any matching layout id, in this case "viewpager" which is a ViewPager but on another view.
I wanted to define TabItem in XML instead of doing it programmatically. As you mentioned, this setupWithViewPager() call resets the text and icon of the tab items to null( It uses the same tab object, just resets its content). I used your approach but made it more reusable. Here is my code:
public class TabLayoutUtil {
public static void setupTabLayoutWithViewPager(TabLayout tabLayout, ViewPager viewPager) {
ArrayList<Pair<CharSequence, Drawable>> tabsContentCopy= new ArrayList<>();
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tabsContentCopy.add(new Pair<>(tab != null ? tab.getText() : null, tab != null ? tab.getIcon() : null));
}
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
if (i<tabsContentCopy.size()) {
tabLayout.getTabAt(i).setText(tabsContentCopy.get(i).first);
tabLayout.getTabAt(i).setIcon(tabsContentCopy.get(i).second);
}
}
}
}

Android: TabLayout not showing any tabs

First time working with com.android.support:design:23.1.1, and having some issues getting TabLayout to work.
My app is basically set up as such:
One main activity called LandingActivity which has a DrawerLayout with menu items in it.
When selecting a menu item, I load different Fragments into a FrameLayout in the LandingActivity.
Some of the loaded Fragments should show tabs at the top, some shouldn't.
My issue is, on the Fragment which is supposed to show tabs at the top, it has extra space in the nav bar like it should have tabs there, but nothing shows.
Code:
activity_landing.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- This LinearLayout represents the contents of the screen -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<!-- The ActionBar displayed at the top -->
<include
layout="#layout/tool_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<!-- The main content view where fragments are loaded -->
<FrameLayout
android:id="#+id/flContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- The navigation drawer that comes from the left -->
<!-- Note that `android:layout_gravity` needs to be set to 'start' -->
<android.support.design.widget.NavigationView
android:id="#+id/nvView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/white"
app:menu="#menu/drawer" />
LandingActivity where I load the fragments:
public void selectDrawerItem(MenuItem menuItem) {
// Create a new fragment and specify the planet to show based on
// position
Fragment fragment = null;
switch(menuItem.getItemId()) {
case R.id.drawer_home:
fragment = HomeFragment.newInstance();
break;
case R.id.drawer_customize:
fragment = CustomizeFragment.newInstance();
break;
default:
fragment = HomeFragment.newInstance();
}
// Insert the fragment by replacing any existing fragment
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
home_fragment.xml (one which has tabs)
<android.support.design.widget.AppBarLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/white"/>
HomeFragment.java
public class HomeFragment extends Fragment {
public static HomeFragment newInstance() {
Bundle args = new Bundle(); alreadySelectedFollowingInfo);
HomeFragment fragment = new HomeFragment();
fragment.setArguments(args);
return fragment;
}
public HomeFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_home, container, false);
final TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tabLayout);
tabLayout.addTab(tabLayout.newTab().setText("One"));
tabLayout.addTab(tabLayout.newTab().setText("Two"));
final ViewPager viewPager = (ViewPager) v.findViewById(R.id.viewpager);
viewPager.setAdapter(new PagerAdapter
(getFragmentManager(), tabLayout.getTabCount()));
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) {
}
});
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return inflater.inflate(R.layout.fragment_home, container, false);
}
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:
BlogFragment tab1 = BlogFragment.newInstance();
return tab1;
case 1:
TrendingFragment tab2 = TrendingFragment.newInstance();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
}
Might not be relevant, but tool_bar.xml used in activity_landing.xml
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:background="?attr/colorPrimary">
That's about all I've got. Can't figure out what's going on.
EDIT:
New code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_home, container, false);
ViewPager viewPager = (ViewPager) v.findViewById(R.id.viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
return v;
}
private void setupViewPager(ViewPager viewPager) {
PagerAdapter adapter = new PagerAdapter(getFragmentManager());
adapter.addFragment(BlogFragment.newInstance(), "ONE");
adapter.addFragment(TrendingFragment.newInstance(), "TWO");
viewPager.setAdapter(adapter);
}
class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
return inflater.inflate(R.layout.fragment_home, container, false);
in your onCreateView means that you return a newly inflated home fragment without any of your initialization code.
You should be returning the view that you created at the beginning of onCreateView:
return v;
Sample PagerAdapter that provides tab titles:
public class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragments = new ArrayList<>();
private final List<String> mFragmentTitles = new ArrayList<>();
public PagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
mFragments.add(fragment);
mFragmentTitles.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitles.get(position);
}
}
And so, your refactored onCreateView code would be something like:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
final TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tabLayout);
final ViewPager viewPager = (ViewPager) v.findViewById(R.id.viewpager);
PagerAdapter adapter = new PagerAdapter(getFragmentManager());
adapter.addFragment(BlogFragment.newInstance(), "One");
adapter.addFragment(TrendingFragment.newInstance(), "Two");
viewPager.setAdapter(adapter);
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return v;
}
Return your initialized infleted view while you are returning
return inflater.inflate(R.layout.fragment_home, container, false);
while you should return view v from first line of onCreateView
final View v = inflater.inflate(R.layout.fragment_home, container, false);

Categories

Resources