how to override and display title of tabs in viewpager2 in tablayout - android

I am using a TabLayout inside a Fragment. The content of the TabLayout (made of 2 fragments) is displayed but not the title of the tabs. I believe it's a layout problem but i'm not sure on how to fix it.
Also what would be the overrided method for ViewPager2 that was used in ViewPager (getPagetitle) ?
main Fragment
public class CommunityFragment extends Fragment {
private TabLayout tbL;
private ViewPager2 vp;
private RecipeViewPagerAdapter rvpa;
public CommunityFragment() {
// Required empty public constructor
}
public static CommunityFragment newInstance(){
return new CommunityFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_community, container, false);
tbL = rootView.findViewById(R.id.tabL);
vp = rootView.findViewById(R.id.pager);
rvpa = new RecipeViewPagerAdapter(this);
vp.setAdapter(rvpa);
rvpa.addFragment(new AllFragment(),"All time");
rvpa.addFragment(new DayFragment(),"Today");
new TabLayoutMediator(tbL, vp, new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
//////title????
}
}).attach();
return rootView;
}
}
Adapter
public class RecipeViewPagerAdapter extends FragmentStateAdapter {
private ArrayList<Fragment> listF = new ArrayList<>();
private ArrayList<String> listT = new ArrayList<>();
public RecipeViewPagerAdapter(#NonNull Fragment fragment) {
super(fragment);
}
#NonNull
#Override
public Fragment createFragment(int position) {
return listF.get(position);
}
//new method ????
public CharSequence getPageTitle(int position){
return listT.get(position);
}
#Override
public int getItemCount() {
return listT.size();
}
public void addFragment(Fragment frag, String title){
listF.add(frag);
listT.add(title);
}
}
fragment layout
<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:orientation="vertical"
tools:context=".fragments.CommunityFragment">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"
app:tabIndicatorColor="#color/yellowCool"/>
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>

put this in your main activity....
myAdapter=new FragmentAdapter(this);
myViewPager2.setAdapter(myAdapter);
String [] tabTtiles={"Home","Chat","Notification","Account"};
new TabLayoutMediator(myTabLayout, myViewPager2,(myTabLayout, position) ->
myTabLayout.setText(tabTtiles[position])).attach();

Your tabLayout doesn't display. Use this:
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" // add this line
/>
TabLayoutMediator:
new TabLayoutMediator(tbL, vp, new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
if(position == 0)
tab.setText("All time");
else
tab.setText("Today");
}
}).attach();

You can use the following adapter for the viewPager2:
public class ViewPagerAdapter extends FragmentStateAdapter {
private static final int CARD_ITEM_SIZE = 10;
public ViewPagerAdapter(#NonNull FragmentActivity fragmentActivity) {
super(fragmentActivity);
}
#NonNull #Override public Fragment createFragment(int position) {
return CardFragment.newInstance(position);
}
#Override public int getItemCount() {
return CARD_ITEM_SIZE;
}
}
on the mainActivity you need to have something inline with the following:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.view_pager);
tabLayout = findViewById(R.id.tabs);
viewPager.setAdapter(new ViewPagerAdapter(this));
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("Tab " + (position + 1));
}
}).attach();
}
}

As per documentation:
The TabLayoutMediator object also handles the task of generating page
titles for the TabLayout object, which means that the adapter class
does not need to override getPageTitle():
And to do that:
TabLayout tabLayout = view.findViewById(R.id.tab_layout);
new TabLayoutMediator(tabLayout, viewPager,
(tab, position) -> tab.setText("OBJECT " + (position + 1))
).attach();

Related

cannot find fragment from viewpager

there is a fragment in my activity in which there is a viewpager which has 5 fragments in it and inside the main activity i need to get one of the fragment from viewpager
Activity
public class MainActivity extends AppCompatActivity {
public void setFragment(){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mainFragment= new MainFragment();
FragmentTransaction fragmentTransaction =getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container, mainFragment,"mainFragment");
fragmentTransaction.commitAllowingStateLoss();
}
}, 250);
}
public void findFragment() {
mainFragment= (MainFragment) getSupportFragmentManager().findFragmentByTag("mainFragment");
viewPager = mainFragment.viewPager;
FragmentOne fragment = (FragmentOne) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + viewPager.getCurrentItem());
}
}
MainFragment
public class MainFragment extends Fragment{
private void initViewPagerAndTabs() {
viewPager = view.findViewById(R.id.viewPager);
pagerAdapter = new PagerAdapter(getChildFragmentManager());
pagerAdapter.addFragment(FragmentOne.newInstance(), "one");
pagerAdapter.addFragment(FragmentTwo.newInstance(), "two");
pagerAdapter.addFragment(FragmentThree.newInstance(), "three");
pagerAdapter.addFragment(FragmentFour.newInstance(), "four");
pagerAdapter.addFragment(FragmentFive.newInstance(), "five");
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = view.findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
viewPager.setCurrentItem(1);
viewPager.setOffscreenPageLimit(3);
}
private static class PagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
private PagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
}
if i use "getFragmentManager()" instead of "getChildFragmentManager()" then it returns the fragment but when i use "getChildFragmentManager()" in viewPager it returns null in activity
Try this Running Code for 1 fragment, may it helps you in your code :
Main Activity
public class OpenQuran extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
TabLayout tabLayoutqaue;
Pager mAdapter;
MediaPlayer mp;
//This is our viewPagerss
ViewPager viewPager;
View mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open_quran);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Read Quran");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Initializing the tablayout
tabLayoutqaue = (TabLayout) findViewById(R.id.tabLayoutqaue);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.pager);
//Creating our pager adapter
mAdapter = new Pager(getSupportFragmentManager());
// 1 Fragment
mAdapter .addFrag(new Quran(), "Quran");
viewPager.setAdapter(mAdapter);
tabLayoutqaue.setupWithViewPager(viewPager);
tabLayoutqaue.setOnTabSelectedListener(this);
}
#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) {
}
Fargment Class :
public class parahlist extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//Returning the layout file after inflating
//Change R.layout.tab1 in you classes
return inflater.inflate(R.layout.activity_parahlist, container, false);}
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
View Pager Class:
public class Pager extends FragmentPagerAdapter {
//integer to count number of tabs
int tabCount;
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
//Constructor to the class
public Pager(FragmentManager fm) {
super(fm);
//Initializing tab count
this.tabCount= tabCount;
}
//Overriding method getItem
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment Fragment, String title) {
mFragmentList.add(Fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
Now This the code Of MainActivity, 2nd Fragment and 3rd one is View Pager class. You dont need to change or edit your View Pager Class. Just Create Java Class and Paste that code as it is.
In Main Activity the Line : mAdapter .addFrag(new Quran(), "Quran"); adding description and Fragment. You can add your own fragment after "new".
After that you have to put Tablayout widget in you Xml as Follows:
<android.support.design.widget.TabLayout
android:id="#+id/tabLayoutqaue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorgreen"
android:minHeight="?attr/actionBarSize"
app:tabIndicatorColor="#color/colorback"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
And View Pager like:
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
/>
You may face some issue regarding tablayout :
Just put this line in your gradle build under dependecies:
compile 'com.android.support:design:25.3.1'
According to your version. for example you have 25.0.1
then line will be :
compile 'com.android.support:design:25.0.1
Still i m here to tell you more. if you got problem!

Replace fragment in a ViewPager

I am trying to replace one of the fragments inside the ViewPager with another one.
The pager is composed by two pages: Fragment1 , Fragment2
inside the fragment2, there is a button. When I click on the button, it will replace the current fragment, Fragment2, with Fragment3. For Fragment2, I want it to be destroyed and not exist anymore.
The implementation Code:
Layout for activity_main:
<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/AppTheme.PopupOverlay">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
main_activity :
private SectionsPageAdapter mSectionsPageAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
mSectionsPageAdapter.clearAll();
}
private void setupViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new Tab1Fragment(), "Tab 1");
adapter.addFragment(new Tab2Fragment(), "Tab 2");
adapter.notifyDataSetChanged()
viewPager.setAdapter(adapter);
}
The Adapter:
public class SectionsPageAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
Fragment2:
public class Tab2Fragment extends Fragment {
private static final String TAG = "Tab2Fragment";
private Button btnTEST;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab2_fragment,container,false);
btnTEST = (Button) view.findViewById(R.id.btnTEST2);
btnTEST.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "TESTING BUTTON CLICK 2", Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
Update :
I tried to implement the method clearAll in the adapter put I noticed the mFragmentList.size() return 0 why ?
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
Log.d("tmz",mFragmentList.size()+" From addFragment"); // return 1 & 2
}
#Override
public int getCount() {
return mFragmentList.size();
Log.d("tmz",mFragmentList.size()+"getCount "); // return 2
}
public void clearAll(){
Log.d("tmz",mFragmentList.size()+" From addFragment"); // return 0 why ?
for(int i=0; i<mFragmentList.size(); i++)
fragMan.beginTransaction().remove(mFragmentList.get(i)).commit();
mFragmentList.clear();
mFragmentList=new ArrayList<Fragment>();
notifyDataSetChanged();
}
remove from mFragmentList (and mFragmentTitleList) and add new, then call notifyDataSetChanged? also add to your SectionsPageAdapter for force redrawing ViewPager when notified.
public int getItemPosition(Object object) {
return POSITION_NONE;
}
not most efficient, but sufficient for your purposes. for adapter:
public void removeLastFragment() {
if(mFragmentList.size()==0)
return;
mFragmentList.remove(mFragmentList.size()-1);
mFragmentTitleList.remove(mFragmentTitleList.size()-1);
}
For zero it was because
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
was repeated twice, and I solve my issue with use replace fragment inside the tab

Hide AppBarLayout using toolbar in fragment in Android

This is my manifest
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
This is my some part of MainActivity.java
public class MainActivity extends AppCompatActivity {
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
Fragment fragment,recepie_fragment,products_fragment,swadeshi_fragment,previous;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_yash);
//setSupportActionBar(toolbar);
//setSupportActionBar(null);
// final View ab=(View)findViewById(R.id.appbarmain);
fragmentManager = getSupportFragmentManager();
fragmentTransaction=fragmentManager.beginTransaction();
recepie_fragment=new Recepie_Fragment();
products_fragment=new Products_Fragment();
swadeshi_fragment=new Swadeshi_Fragment();
fragment=recepie_fragment;//new Fragment();
fragmentTransaction.replace(R.id.bglayout,fragment);
fragmentTransaction.commit();
previous=fragment;
BottomBar bb=BottomBar.attach(this,savedInstanceState);
bb.setActiveTabColor("RED");
bb.setItemsFromMenu(R.menu.bottom_buttons, new OnMenuTabSelectedListener() {
#Override
public void onMenuItemSelected(int menuItemId) {
fragmentTransaction=fragmentManager.beginTransaction();
switch(menuItemId)
{
case R.id.button1:
previous=fragment;
// ab.setAlpha(0);
fragment=recepie_fragment;//new Recepie_Fragment();
// fragment.setRetainInstance(true);
break;
case R.id.button2:
//getSupportActionBar().show();
previous=fragment;
fragment=products_fragment;//new Products_Fragment();
//fragment.setRetainInstance(true);
break;
case R.id.button3:
previous=fragment;
//getSupportActionBar().show();
fragment=swadeshi_fragment;//new Swadeshi_Fragment();
//fragment.setRetainInstance(true);
break;
}
fragmentTransaction.replace(R.id.bglayout,fragment);
fragmentTransaction.commit();
}
});
}
Here is my RecepieFragment.java
public class Recepie_Fragment extends Fragment {
View rootView;
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
int logo_ids[]={R.drawable.main_course,R.drawable.cakes,R.drawable.specials};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
void setupTabIcons()
{
tabLayout.getTabAt(0).setIcon(logo_ids[0]);
tabLayout.getTabAt(1).setIcon(logo_ids[1]);
tabLayout.getTabAt(2).setIcon(R.drawable.extra);
// tabLayout.getTabAt(1).setCustomView();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//getActivity().getApplication().setTheme(R.style.AppTheme_NoActionBar);
rootView=inflater.inflate(R.layout.recepie_viewpager, container, false);
//getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
toolbar=(Toolbar)rootView.findViewById(R.id.toolbar_yash);
// ((AppCompatActivity) getActivity()).findViewById(R.id.toolbar_yash).animate().translationY(-(R.id.toolbar_yash).getBottom()).setInterpolator(new AccelerateInterpolator()).start();
viewPager = (ViewPager)rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
setRetainInstance(true);
viewPager.setOffscreenPageLimit(3);
tabLayout = (TabLayout)rootView. findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
//actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
private int previousState, currentState;
#Override
public void onPageScrollStateChanged(int state) {
int currentPage = viewPager.getCurrentItem(); //ViewPager Type
if (currentPage == 2 || currentPage == 0) {
previousState = currentState;
currentState = state;
if (previousState == 1 && currentState == 0) {
viewPager.setCurrentItem(currentPage == 0 ? 2 : 0);
}
}
}
});
return rootView;
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getChildFragmentManager());//(getActivity().getSupportFragmentManager());
adapter.addFrag(new Main_Course(), "");
adapter.addFrag(new Cakes(), "");
adapter.addFrag(new Specials(), "");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
And this the xml file i am using :
tools:context=".activity.activity.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/appbarmain"
android:theme="#style/AppTheme.NoActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_yash"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.NoActionBar" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
Below type of visualisation is created when I'm trying to hide the toolbar/actionbar in recepies fragment. What I want is whenever I move into products or swadeshi fragment I get this action bar but when in recepie fragment my actionbar hides and screen consists of my viewpager of 3 elements as shown of cake but instead a blank is created.

Tabs with in the Tabs in android studio

I just want to implements Tabs with in the Tabs. If it is possible than please share the code
See image below for reference
This is the answer of my question. I set the tabs with in the Tabs. Basically set the tab in fragment:
My java code:
public class SD extends Fragment {
View view;
PagerAdapter adapter;
public SD() {
// Required empty public constructor
}
private void setupViewPager(ViewPager viewPager) {
///Here we have to pass ChildFragmentManager instead of FragmentManager.
adapter = new PagerAdapter(getChildFragmentManager());
adapter.addFragment(new Sim1Detail(), "Sim 1");
adapter.addFragment(new Sim2Detail(), "Sim 2");
viewPager.setAdapter(adapter);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.sd, container, false);
super.onCreate(savedInstanceState);
// ButterKnife.bind(getActivity(), view);
final ViewPager viewPager = ButterKnife.findById(view, R.id.viewpager);
setupViewPager(viewPager);
TabLayout tabLayout = ButterKnife.findById(view, R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return view;
}
#Override
public void onDestroyView() {
super.onDestroyView();
// ButterKnife.unbind(getActivity);
}
static 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);
}
}
}
<?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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
here it is ..

Android view pager not displaying Fragment when it is called again

I have a slider menu in my application, when I click on an item in the menu it displays the corresponding fragment. That fragmet has a tablayout and a viewpager. The Fragment xml is given below
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:background="#color/colorPrimary"
app:tabSelectedTextColor="#color/textColorPrimary"
app:tabTextColor="#color/colorAccent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_below="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
Below given is the code snippet of the fragment clicked on the slider menu
public class MyCoursesFragment extends Fragment {
private TabLayout tabLayout;
private ViewPager viewPager;
public MyCoursesFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getFragmentManager());
adapter.addFragment(new ScheduledFragment(), "SCHEDULED");
adapter.addFragment(new LiveStreamingFragment(), "LIVE STREAMING");
adapter.addFragment(new UpcomingFragment(), "UPCOMING");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(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);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("mlearning", "inside my course");
View rootView = inflater.inflate(R.layout.fragement_courses, container, false);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
There are three tabs in the above fragment. The xml for each fragment contains a list view, the xml is given below.
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lvList"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:backgroundTint="#888686" />
The code for the tablayout fragment is given below:
public class ScheduledFragment extends Fragment {
public ScheduledFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("mlearning", "inside scheduled");
View rootView = inflater.inflate(R.layout.fragment_scheduled, container, false);
ArrayList<CoursePojo> searchResults = GetSearchResults();
final ListView lv1 = (ListView) rootView.findViewById(R.id.lvList2);
lv1.setAdapter(new MyCustomCourseList(getActivity(), searchResults));
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv1.getItemAtPosition(position);
CoursePojo fullObject = (CoursePojo) o;
//Toast.makeText(getBaseContext(), "You have chosen: " + " " + fullObject.getId(), Toast.LENGTH_LONG).show();
}
});
return rootView;
}
private ArrayList<CoursePojo> GetSearchResults(){
ArrayList<CoursePojo> results = new ArrayList<CoursePojo>();CoursePojo coursePojo3=new CoursePojo();
coursePojo3.setName("Android");
coursePojo3.setDesc("First os was released without a phone ");
coursePojo3.setStartdate("20 Mar");
coursePojo3.setEndDate("8 Apr");
coursePojo3.setProgress("40");
results.add(coursePojo3);
// Inflate the layout for this fragment
return results;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}}
Initially when I click on the menu fragment, the values in the tab fragment comes as it is mentioned in the code. But if I again tap on the menu slider the items in the tab layout are not displaying.And also some tabs empty or some tabs are having some value. Where am I going wrong?
Use FragmentStatePagerAdapter instant of FragmentPagerAdapter.
Try populating data in List inside onResume()

Categories

Resources