Android add fragment and tab after load? - android

I have a FragmentActivity with two Fragments in it and a sliding tab layout:
String titles[] = new String[] {"Tab One", "Tab Two"};
int numTabs = titles.length;
EventAdapter adapter = new EventAdapter(getSupportFragmentManager(), titles, numTabs);
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
SlidingTabLayout sliding_tabs = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
sliding_tabs.setDistributeEvenly(true);
sliding_tabs.setViewPager(pager);
With the FragmentPagerAdapter:
private class EventAdapter extends FragmentPagerAdapter {
private List<String> titles;
private int numTabs;
public void addTab (String title) {
this.titles.add(title);
this.numTabs++;
this.notifyDataSetChanged();
}
public EventAdapter(FragmentManager fm, List<String> mTitles, int mNumTabs) {
super(fm);
this.titles = mTitles;
this.numTabs = mNumTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 2:
return new FragThree();
case 1:
return new FragTwo();
default:
return new FragOne();
}
}
#Override
public String getPageTitle(int position) {
return titles.get(position);
}
#Override
public int getCount() {
return numTabs;
}
}
Some time down the line, I would like to dynamically add the third tab to this layout. Is there a way to do this in code? As you can see, I already have the PagerAdapter set up to catch the third tab. I just need to load it in...

You need to add this method to your adapter EventAdapter :
public void addTab (String title) {
this.titles.add(title);
// this is the variable returned from getCount method
this.numbTabs++;
this.notifyDataSetChanged();
}
Main purpose is to add the tab and call notifydatasetchanged.
Now call addTab on this adapter's object and tab will be added.
after addTab do sliding_tab.setViewPager(this.pager);
Please accept if this solves the purpose.

Related

Android - ViewPager third tab has not shown

i have a viewPager that contains 3 tabs fragments.
the first and the second fragments works fine but when i sweep to the third tab
i do not see him.
the third tab has shown only when the activity with the viewPager has reload(move to another activity and return).
my code:
private void setupViewPager(ViewPager viewPager) {
adapter = new PagerAdapter(getSupportFragmentManager());
adapter.addFragment(new Fragment1(), Constants.TAB_0);
adapter.addFragment(new Fragment2(), Constants.TAB_1);
adapter.addFragment(new Fragment3(), Constants.TAB_2);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(3);
}
pager adapter:
public class PagerAdapter extends FragmentPagerAdapter {
/*
* Arraylist used to contain the fragments
* and contain fragments title's
*/
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public PagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
//Adds the fragment and it's title. Called in MainActivity
public void addFragment(Fragment fragment, String title) {
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
//Retrieves the title of the tab
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Here is my adapter, on getItem I set the fragment object to the Fragment activity.
public class SectionPagerAdapter extends FragmentPagerAdapter {
Fragment fragment;
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0){
fragment = new FragmentOne();
}
else if (position == 1){
fragment = new FragmentTwo();
}
else if (position == 2){
fragment = new FragmentThree();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "name one";
case 1:
return "name two";
case 2:
return "name three";
}
return null;
}
}
Then in my main activity I call it like so:
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
SectionPagerAdapter sectionPagerAdapter = new SectionPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(sectionPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
Try replacing your code with above and let me know if it helps!
USE new PagerAdapter(getChildSupportFragmentManager());instead of getSupportFragmentManager()
Try this one !!

Android Recycler View in tab layout

I'm trying to set up a tablayout with 3 tabs, each tab will have a recycler view in it. I found this question: How to implement RecyclerView with CardView rows in a Fragment with TabLayout
Which is similier to what I want, I'm trying to set this up, then I'll set up my data retrieval after I get this working.
The problem I'm getting now it setting up the PagerAdapter. Here is my code:
public class WorkoutDaysActivity extends BaseActivity{
ListView mListView = new ListView(this);
ArrayList<CustomObject> w29w1m;
CustomListViewAdapter mCustomListViewAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.workout_days);
mToolBar = activateToolbar();
setUpNavigationDrawer();
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
PagerAdapter pagerAdapter =
new PagerAdapter(getSupportFragmentManager(), WorkoutDaysActivity.this)
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
#Override
public void onResume() {
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[] { "Tab One", "Tab Two", "Tab Three" };
Context context;
public PagerAdapter(FragmentPagerAdapter fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new WorkoutDetailFragment();
case 1:
return new WorkoutDetailFragment();
case 2:
return new WorkoutDetailFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(WorkoutDaysActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}}
The first spot where I'm getting an error is
PagerAdapter pagerAdapter =
new PagerAdapter(getSupportFragmentManager(), WorkoutDaysActivity.this)
viewPager.setAdapter(pagerAdapter);
The error is:
PagerAdapter (android.support.v4.app.FragmentPagerAdapter, Context) in PagerAdapter cannot be applied to: (android.support.v4.app.FragmentManager, WorkoutDaysActivity.this)
The android.support.v4.app.FragmentManager is the part underlined in red. The second error is in this part:
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[] { "Tab One", "Tab Two", "Tab Three" };
Context context;
public PagerAdapter(FragmentPagerAdapter fm, Context context) {
super(fm);
this.context = context;
}
The error is in the super(fm); part, and it states:
FragmentPagerAdapter (android.support.v4.app.FragmentManager) in FragmentPagerAdapter cannot be applied to: android.support.v4.app.FragmentPagerAdapter
I feel like this would be a simple error with importing the wrong thing, but my attempts to fix it failed. Any help greatly appreciated thank you!
Your PagerAdapter class extends FragmentPagerAdapter. Then its constructor TAKES a FragmentPagerAdapter to initialize. So to initialize a FragmentPagerAdapter you need a FragmentPagerAdapter already?
I think that parameter is supposed to be a FragmentManager.

opening a layout (xml) inside a fragment instead of string text input

Problem: I was modifying a small app where three tabs are there in fragment but all refers to text string. I wanted to use layout xml so that I can make good graphics in it. How can I do it in this code:
Information_tab refers to a string where I can put text, but I want a layout.
public class AdapterInformation extends FragmentPagerAdapter {
public AdapterInformation(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
Bundle bundle = new Bundle();
int imgResId = 0;
int tab = 0;
int colorResId = 0;
switch (index) {
case 0:
tab = R.string.information_tab1;
break;
case 1:
tab = R.string.information_tab2;
break;
case 2:
tab = R.string.information_tab3;
break;
}
bundle.putInt("image", imgResId);
bundle.putInt("tab",tab);
bundle.putInt("color", colorResId);
SwipeTabFragment swipeTabFragment = new SwipeTabFragment();
swipeTabFragment.setArguments(bundle);
return swipeTabFragment;
}
#Override
public int getCount() {
return 3;
}}
you can add fragment layout like this.
private void setupViewPager(final ViewPager viewPager) {
final ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneFragment(), "Pending Upload");
adapter.addFragment(new TwoFragment(), "Complete Upload");
viewPager.setAdapter(adapter);
}
and your fragmentPagerAdapter code is like this:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager)
{
super(manager);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#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);
}
}
and also add your setupViewPager method in onCreate()
viewPager = (ViewPager) findViewById(R.id.viewpager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
setupViewPager(viewPager)
tabLayout.setupWithViewPager(viewPager);
Note: Do not use getItemPosition() method if its possible.. it
will produce redundancy of your listItems or ArrayList.. bcz every
time you swipe to other layout it will refresh page automatically..
its good if want this facility.. but you have write some code
regarding to handle this method.. and its also going to slow your
swipe animation if you have large amount of data.
For more information about tab layout and fragment: you can refer this one:
http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/

View pager fragments and Tabs are out of sync android

In my project I have a tab layout and a fragments viewpager. When I load the fragments and tabs the tab index and the displayed fragment is out of sync, and also when I swipe back and forth the fragments are not in sync with the tabs. I checked the getItem(int position) and the getTitle(int position) methods both have the same position number and the corresponding entries in the ArrayList<Fragments> and the ArrayList<String> (for tab headings) are correct but some how the tabs display is out of sync with the view pager.
Here is my fragmentPagerAdapter.java
public class DetailsFragmentPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragments;
private ArrayList<String> titles;
public DetailsFragmentPagerAdapter(FragmentManager fm) {
super(fm);
fragments = new ArrayList<>();
titles = new ArrayList<>();
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return titles.size();
}
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
public void setFragment(Fragment fragment, String title) {
fragments.add(fragment);
titles.add(title);
notifyDataSetChanged();
}
}
this is activity on create.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
tabLayout = (TabLayout) findViewById(R.id.detailsTabs);
viewPager = (ViewPager) findViewById(R.id.viewPager);
new GetCategoriesAsync2().execute();
}
the async task's doInBackground is calling is preparing arraylist
and the onPostExecute
#Override
protected void onPostExecute(Void aVoid) {
int size = lists.size();
ArrayList<Fragment> fragments = new ArrayList<>(size);
ArrayList<String> titles = new ArrayList<>(size);
for (int i = 0; i < lists.size(); i++) {
ArrayList<String> x = lists.get(i);
titles.add(x.remove(0));
fragments.add(DetailsListFragment.newInstance(x));
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentPagerAdapter = new DetailsFragmentPagerAdapter(fragmentManager);
fragmentPagerAdapter.setFragments(fragments,titles);
viewPager.setAdapter(fragmentPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
progressDialog.dismiss();
}
I am using design support library 23.0.1 and the build target is 23.
how can I fix this tab layout out of sync?
if you use a TabLayout, you need to connect it to the adapter
If you're using a ViewPager together with this layout, you can use
setTabsFromPagerAdapter(PagerAdapter) which will populate the tabs
using the given PagerAdapter's page titles. You should also use a
TabLayout.TabLayoutOnPageChangeListener to forward the scroll and
selection changes to this layout like so:
ViewPager viewPager = ...;
TabLayout tabLayout = ...;
viewPager.addOnPageChangeListener(new TabLayoutOnPageChangeListener(tabLayout));
Try this, it worked for me
public class DetailsFragmentPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragments= new ArrayList<Fragment>();
private final List<String> titles= new ArrayList<String>();
public DetailsFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public CharSequence getPageTitle(int position) {
return titles.get(position);
}
public void setFragment(Fragment fragment, String title) {
fragments.add(fragment);
titles.add(title);
}
}
And Change
fragmentPagerAdapter.setFragments(fragments,titles); To
for (int i=0;i<fragments.size();i++)
{
adapter.setFragments(fragments.get(i),titles.get(i));
}
Check this out
it's a demo app that uses a TabLayout with a ViewPager
https://github.com/chrisbanes/cheesesquare
and if you don't know the number of the fragments that you will have in the ViewPager
your pageadapter should extends FragmentStatePagerAdapter
https://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter.html

Add a tab to SlidingTabLayout dynamically (Android)

I followed these guidelines to create a Sliding tab layout with fragments. The problem is that I want to dynamically add a tab to the SlidingTabLayout. The following code creates a fragment but it isn't displayed. How can i attach it to the SlidingTabLayout?
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
tableFragment = (ReportTableFragment) adapter.getItem(1);
fragmentTransaction.replace(R.id.pager, tableFragment, tableFragment.getClass().getName());
fragmentTransaction.commit();
This is my ViewPagerAdapter class
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs; // Store the number of tabs, this will also be passed when the ViewPagerAdapter is created
// Build a Constructor and assign the passed Values to appropriate values in the class
public ViewPagerAdapter(FragmentManager fm,CharSequence mTitles[], int mNumbOfTabsumb) {
super(fm);
this.Titles = mTitles;
this.NumbOfTabs = mNumbOfTabsumb;
}
//This method return the fragment for the every position in the View Pager
#Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
//ReportMapFragment reportMapTab = new ReportMapFragment();
//return reportMapTab;
SupportMapFragment mapTab = new SupportMapFragment();
return mapTab;
}
else
{
return ReportTableFragment.newInstance(1);
}
}
// This method return the titles for the Tabs in the Tab Strip
#Override
public CharSequence getPageTitle(int position) {
return Titles[position];
}
// This method return the Number of tabs for the tabs Strip
#Override
public int getCount() {
return NumbOfTabs;
}
}
The solution is pretty easy :)
You should add this methods to your 'ViewPagerAdapter' and change the CharSequence by this
List<String> titles = new ArrayList<String>();
Now the constructor should be:
public ViewPagerAdapter(FragmentManager fm, List<String> mTitles, int mNumbOfTabsumb) {
super(fm);
this.titles = mTitles;
this.numbOfTabs = mNumbOfTabsumb;
}
Methods to add to the 'ViewPagerAdapter':
public void addTab (String title) {
this.titles.add(title);
this.numbOfTabs++;
this.notifyDataSetChanged();
}
public void deleteTab (int position) {
this.titles.remove(position);
this.numbOfTabs--;
this.notifyDataSetChanged();
}
And from your activity or wherever you call the SlidingTabLayout:
this.mAdapter.addTab("NewTab"); // add a new tab
this.mAdapter.deleteTab(0); // or delete a current tab
this.mTabs.setViewPager(this.mPager); // don't forget this line, is the key
Pay attention to the 'getItem' method in your 'ViewPagerAdapter' cause now you are adding tabs dynamically ;)
I.

Categories

Resources