so I wanted a tablayout and a viewpager to be able to swipe through different fragments.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
tabLayout = (TabLayout) view.findViewById(R.id.tabLayout);
viewPager = (ViewPager) view.findViewById(R.id.viewPager);
viewPagerAdapter = new ViewPagerAdapter(getFragmentManager());
viewPagerAdapter.addFragments(new AFragment(), "Test1", getContext());
viewPagerAdapter.addFragments(new BFragment(), "Test2", getContext());
viewPagerAdapter.addFragments(new CFragment(), "Test3", getContext());
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
return view;
}
And my ViewPagerAdapter class looks like this:
public class ViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragments = new ArrayList<>();
ArrayList<String> tabTitles = new ArrayList<>();
Context context;
public void addFragments(Fragment fragments, String titles, Context context) {
this.fragments.add(fragments);
this.tabTitles.add(titles);
this.context = context;
}
public ViewPagerAdapter(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 tabTitles.get(position);
}
}
So the adapter I set my viewPager to contains all the information such as the titles for my tabLayout and the amount of fragments. Is that correct?
So what I want to do now is replace the titles on my tabLayout with certain icons.
Am I supposed to remove the String parameter in my ViewPagerAdapter constructor and delete my Arraylist or do I have to pass an empty String?
What code do I need to add to my ViewPageAdapter class in order to be able to add icons instead of the Strings to the layout?
I found a possible solution here: How to add page title and icon in android FragmentPagerAdapter
So I changed my method to that:
#Override
public CharSequence getPageTitle(int position) {
myDrawable = ContextCompat.getDrawable(context, R.drawable.ic_mail_outline_black_24dp);
SpannableStringBuilder sb = new SpannableStringBuilder(" Page #"+ position); // space added before text for convenience
myDrawable.setBounds(0, 0, myDrawable.getIntrinsicWidth(), myDrawable.getIntrinsicHeight());
ImageSpan span = new ImageSpan(myDrawable, ImageSpan.ALIGN_BASELINE);
sb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return sb;
}
That changed my titles to PAGE #0 #1 ... but didn't add the icon to my TabLayout.
Thank you!
EDIT:
This works too. Still don't know what I did wrong though
tabLayout.getTabAt(i).setIcon();
Please use this code for icon
mTabLayout.setupWithViewPager(mViewPager);
for (int i = 0; i < mTabLayout.getTabCount(); i++) {
mTabLayout.getTabAt(i).setIcon(R.drawable.your_icon);
}
Please replace this code will work
#Override
public CharSequence getPageTitle(int position) {
myDrawable = ContextCompat.getDrawable(context, R.drawable.ic_mail_outline_black_24dp);
title = tabTitles.get(position);
SpannableStringBuilder sb = new SpannableStringBuilder(" " + title); // space added before text for convenience
try {
myDrawable.setBounds(5, 5, myDrawable.getIntrinsicWidth(), myDrawable.getIntrinsicHeight());
ImageSpan span = new ImageSpan(myDrawable, DynamicDrawableSpan.ALIGN_BASELINE);
sb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
} catch (Exception e) {
// TODO: handle exception
}
tabTitles.set(position,sb);
return tabTitles.get(position);
}
Related
I have simple problem.. I have MainActivity.. inside it i have 5 fragments and i can move using bottom navigation bar without problem!
In first fragment (Profile) i have inside that tow fragment using Tablayout and Viewpager..
First Fragment (Friends) Second Fragment (Users)..
My problem when i run app and open (Profile) the tow fragments (Friends and Users)
Working 100% just in first time.. when i come back to other fragment using bottom bar and come back to friends or users is empty and not load !
I want attach some of my codes you will need it..
Profile Fragment:
mSectionsPageAdapter = new
SectionsPageAdapter(getActivity().getSupportFragmentManager());
mViewPager = (ViewPager) v.findViewById(R.id.container);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
mSectionsPageAdapter.notifyDataSetChanged();
private void setupViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new
SectionsPageAdapter(getActivity().getSupportFragmentManager());
adapter.addFragment(new FriendsFragment(), "Friends");
adapter.addFragment(new UsersFragment(), "Online");
viewPager.setAdapter(adapter);
}
SectionsPageAdapter:
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();
}}
I try to add this in Friends Fragment and Users Fragment the problem was solved but the content duplicated in first time run only.
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
getFragmentManager().beginTransaction().detach(this).attach(this).commit();
}
}
SectionsPageAdapter:
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();
}}
A possible reason for your problems could be you are mixing up FragmentManagers.
In your Activity to handle the bottom navigation you should use Activity#getSupportFragmentManager().
But for any of the Fragments inside that activity, if you want to have children/nested fragments. You should use Fragment#getChildFragmentManager().
So in your profile fragment, while populating the two tabs pager, you should pass it Fragment#getChildFragmentManager() instead of getActivity().getSupportFragmentManager()
You can use interface to solve this problem. Implement interface in your "User" & "Friend" fragments & call the interface method when your "Profile" fragments "OnCreateView" is called. You can load data when interface method is called. For reference, Please check this link:
Communicating with Other Fragments
EDIT
Sorry,you can load data without using Interface. Here is some sample code:
Profile Fragment:
ProfileFragment extends Activity {
FriendsFragment friends;
UsersFragment users;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mSectionsPageAdapter = new
SectionsPageAdapter(getActivity().getSupportFragmentManager());
mViewPager = (ViewPager) v.findViewById(R.id.container);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) v.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
mSectionsPageAdapter.notifyDataSetChanged();
friends.update();
users.update();
}
private void setupViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new
SectionsPageAdapter(getActivity().getSupportFragmentManager());
friends = new FriendsFragment();
users = new UsersFragment();
adapter.addFragment(friends, "Friends");
adapter.addFragment(users, "Online");
viewPager.setAdapter(adapter);
}
Friends Fragment:
FriendFragment extends Activity {
public void update(){
// load data
}
jest Use
ViewPagerAdapter(getChildFragmentManager())
getChildFragmentManager()
In a simple tabLayout view viewPager setup I am unable to correctly pass through the selected tab to the fragment within it. As tabs are selected left to right (i.e tab 1 -> tab x) the tab is correctly interpreted, but as they are selected right to left, 0 is returned.
Here is the important code:
Activity including tabLayout:
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new OwnPagerAdapter(getSupportFragmentManager(), NavDrawer.this));
tabLayout.setupWithViewPager(viewPager);
PagerAdapter:
public class OwnPagerAdapter extends FragmentPagerAdapter {
private int TAB_COUNT = 7;
private String tabTitles[] = new String[] {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" };
private Context context;
public OwnPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public Fragment getItem(int position) {
return OwnTimetableFragment.newInstance(position - 1);
}
#Override
public int getCount() {
return TAB_COUNT;
}
#Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
Fragment:
public class OwnTimetableFragment extends Fragment {
public static final String ARG_DAY = "ARG_DAY";
private int mDay;
public static OwnTimetableFragment newInstance(int day) {
Bundle args = new Bundle();
args.putInt(ARG_DAY, day);
OwnTimetableFragment fragment = new OwnTimetableFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDay = getArguments().getInt(ARG_DAY);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View tabView = inflater.inflate(R.layout.fragment_own_timetable, container, false);
Log.e("mDay", mDay + "");
return tabView;
}
The log method call in the onCreateView of the fragment will correctly return numbers 0->6 as the tabs are swiped through left to right, but as soon as a tab left of the current tab is selected, it will return 0, which will become the new origin (i.e one tab right will become 1)
Seems as though there is something going on with fragments coming in and out of focus that might be causing this?
First of all, you are passing pos - 1 in your new instance, because of which, your first tab will display log as -1. If you want correct value, only pass pos in newInstance.
Other than that, make sure you are not passing any setOffscreenPageLimit in viewPager. Everthing else in your code seems to be okay.
Let me know your exact issue if you are still facing it.
so I'm working on an app that utilizes a fixed 2 tabs within a view pager. I have a RecyclerView inside of a ViewPager but the RecyclerView is not responding to horizontal swipes. I have disabled swiping to change pages within the ViewPager by overriding onInterceptTouchEvent and onTouchEvent. I've called setFocusable(false) and setFocusableInTouchMode(false) on the view pager to no avail. Any ideas?
// ViewPager code
pager = (NoSwipePager) findViewById(R.id.pager);
pager.setFocusable(false);
pager.setFocusableInTouchMode(false);
adapter = new FormTabAdapter(getSupportFragmentManager(), form, editing);
pager.setAdapter(adapter);
pager.setCurrentItem(0);
tabs = (PagerTabStrip) findViewById(R.id.tab_strip);
tabs.setTabIndicatorColor(Color.WHITE);
tabs.setBackgroundColor(Color.parseColor("#A52A2A"));
tabs.setTextColor(Color.WHITE);
// RecyclerView code
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(act);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
rv.setLayoutManager(linearLayoutManager);
((SimpleItemAnimator) rv.getItemAnimator()).setSupportsChangeAnimations(false);
elementsAdapter = new ElementsAdapter(listener, act, new LinkedList<>(elements), editing);
rv.setAdapter(elementsAdapter);
ItemTouchHelper.Callback callback = new ElementTouchHelper(elementsAdapter);
ItemTouchHelper helper = new ItemTouchHelper(callback);
helper.attachToRecyclerView(rv);
For that you need to off viewpager swaping both are not working at same time.
Too disable swip of viewpager use below code
public class MyViewPager extends ViewPager {
private boolean enabled;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true; // default swipe enable is true
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
// true - enable swipe
// false - disable swipe
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
}
and use below code while using viewpager in .xml file
<package.MyViewPager
android:id="#+id/viewPager"
android:layout_height="match_parent"
android:layout_width="match_parent" />
Hope these answer helps you.
These same approach you can use use it for recyclerview also if you required in future.
Hope these help you.
You can use fragment to show RecycleView.
For example:
You will create a class Adapter to manage.
public class HomeFragmentAdapter extends FragmentPagerAdapter {
private final ArrayList<Fragment> mFragment = new ArrayList<>();
private final ArrayList<String> mFragmentTitle = new ArrayList<>();
public HomeFragmentAdapter(FragmentManager fragmentManager){
super(fragmentManager);
}
public void addFragment(Fragment fragment, String title){
mFragment.add(fragment);
mFragmentTitle.add(title);
}
#Override
public Fragment getItem(int position) {
return mFragment.get(position);
}
#Override
public int getCount() {
return mFragment.size();
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitle.get(position);
}
}
And after that you will add more fragment which include any RecycleView you need.
public class HomeFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
Menu mMenu;
public HomeFragment(){
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.fragment_layout_home, null);
tabLayout = (TabLayout) view.findViewById(R.id.tab_home);
viewPager = (ViewPager) view.findViewById(R.id.viewpager_home);
if(viewPager != null){
setupViewPager(viewPager);
}
tabLayout.setTabMode(TabLayout.MODE_FIXED);
tabLayout.setupWithViewPager(viewPager);
return view;
}
private void setupViewPager(ViewPager viewPager){
HomeFragmentAdapter adapter = new HomeFragmentAdapter(getChildFragmentManager());
adapter.addFragment(new ExpenseFragment(), "Expense");
adapter.addFragment(new IncomeFragment(), "Income");
viewPager.setAdapter(adapter);
}
T hope it could been help you.
Hi I want to send the data ArrayList<Division> to Fragment class ListContentFragment.
In MainActivity I am making a network call to get the data(JSON) and then parsing it to create ArrayList<Division>, now i want to populate the list view with the data i received (now in ArrayList<Division>)
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Adding Toolbar to Main screen
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Setting ViewPager for each Tabs
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
// Set Tabs inside Toolbar
TabLayout tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
// Create Navigation drawer and inlfate layout
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
// Adding menu icon to Toolbar
ActionBar supportActionBar = getSupportActionBar();
if (supportActionBar != null) {
VectorDrawableCompat indicator
= VectorDrawableCompat.create(getResources(), R.drawable.ic_menu, getTheme());
indicator.setTint(ResourcesCompat.getColor(getResources(),R.color.white,getTheme()));
supportActionBar.setHomeAsUpIndicator(indicator);
supportActionBar.setDisplayHomeAsUpEnabled(true);
}
// Set behavior of Navigation drawer
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
// Set item in checked state
menuItem.setChecked(true);
// TODO: handle navigation
Toast.makeText(MainActivity.this, "Clicked: " + menuItem.getTitle(), Toast.LENGTH_SHORT).show();
// Closing drawer on item click
mDrawerLayout.closeDrawers();
return true;
}
});
// Adding Floating Action Button to bottom right of main view
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Snackbar.make(v, "Hello Snackbar!",
Snackbar.LENGTH_LONG).show();
}
});
// Network request test with volley
NetworkRequests networkRequest = new NetworkRequests(this);
networkRequest.fetchDummyData();
divisionList = networkRequest.getDivisions();
}
// Add Fragments to Tabs
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getSupportFragmentManager());
adapter.addFragment(new ListContentFragment(), "List");
adapter.addFragment(new TileContentFragment(), "Tile");
adapter.addFragment(new CardContentFragment(), "Card");
viewPager.setAdapter(adapter);
}
Fragment (currently its hard coded, want to populate with the ArrayList)
public class ListContentFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
RecyclerView recyclerView = (RecyclerView) inflater.inflate(
R.layout.recycler_view, container, false);
ContentAdapter adapter = new ContentAdapter(recyclerView.getContext());
recyclerView.setAdapter(adapter);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return recyclerView;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public ImageView avator;
public TextView name;
public TextView description;
public ViewHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.item_list, parent, false));
avator = (ImageView) itemView.findViewById(R.id.list_avatar);
name = (TextView) itemView.findViewById(R.id.list_title);
description = (TextView) itemView.findViewById(R.id.list_desc);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, DetailActivity.class);
intent.putExtra(DetailActivity.EXTRA_POSITION, getAdapterPosition());
context.startActivity(intent);
}
});
}
}
/**
* Adapter to display recycler view.
*/
public static class ContentAdapter extends RecyclerView.Adapter<ViewHolder> {
// Set numbers of List in RecyclerView.
private static final int LENGTH = 18;
private final String[] mPlaces;
private final String[] mPlaceDesc;
private final Drawable[] mPlaceAvators;
public ContentAdapter(Context context) {
Resources resources = context.getResources();
mPlaces = resources.getStringArray(R.array.places);
mPlaceDesc = resources.getStringArray(R.array.place_desc);
TypedArray a = resources.obtainTypedArray(R.array.place_avator);
mPlaceAvators = new Drawable[a.length()];
for (int i = 0; i < mPlaceAvators.length; i++) {
mPlaceAvators[i] = a.getDrawable(i);
}
a.recycle();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()), parent);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.avator.setImageDrawable(mPlaceAvators[position % mPlaceAvators.length]);
holder.name.setText(mPlaces[position % mPlaces.length]);
holder.description.setText(mPlaceDesc[position % mPlaceDesc.length]);
}
#Override
public int getItemCount() {
return LENGTH;
}
}
}
If you want to pass an ArrayList to your fragment, then you need to make sure the Model class is implements Parcelable.
Here i can show an example.
public class ObjectName implements Parcelable {
public ObjectName(Parcel in) {
super();
readFromParcel(in);
}
public static final Parcelable.Creator<ObjectName> CREATOR = new Parcelable.Creator<ObjectName>() {
public ObjectName createFromParcel(Parcel in) {
return new ObjectName(in);
}
public ObjectName[] newArray(int size) {
return new ObjectName[size];
}
};
public void readFromParcel(Parcel in) {
Value1 = in.readInt();
Value2 = in.readInt();
Value3 = in.readInt();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(Value1);
dest.writeInt(Value2);
dest.writeInt(Value3);
}
}
then you can add ArrayList<ObjectName> to a Bundle object.
ArrayList<ObjectName> arraylist = new Arraylist<ObjectName>();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("arraylist", arraylist);
fragment.setArguments(bundle);
After this you can get back this data by using,
Bundle extras = getIntent().getExtras();
ArrayList<ObjectName> arraylist = extras.getParcelableArrayList("arraylist");
At last you can show list with these data in fragment. Hope this will help to get your expected answer.
I was also stuck with the same problem .
You can try this.
Intead of sending the arraylist as bundle to fragment.Make the arraylist to be passed,as public and static in the activity.
public static Arraylist<Division> arraylist;
Then after parsing and adding the data in the arraylist make the call to the fragment.In the fragment you can the use the arraylist as:
ArrayList<Division> list=MainActivity.arraylist;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.v(TAG, "onCreateView");
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
// setting up the view pager and tab layout
mViewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
mTabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout);
PageAdapter adapter = new PageAdapter(getFragmentManager());
mViewPager.setAdapter(adapter);
mTabLayout.setupWithViewPager(mViewPager);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
return rootView;
}
My custom pager adapter looks like this:
public class PageAdapter extends FragmentStatePagerAdapter {
public PageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new GroupTabFragment(position);
}
#Override
public CharSequence getPageTitle(int position) {
String title = "";
switch (position) {
case 0:
title = "Game"; // this is from a template, i have to
break; // return title dynamically
case 1:
title = "Movie";
break;
}
return title;
}
#Override
public int getCount() {
return 2; // the tabs number is a subject of change
} // i don't know it from the begining
}
The problem i have is that i have to add or remove a tab when a button is clicked, or something like this.
Each tab will display a classic list of objects.
Thank you.
There are 2 ways doing this although ViewPager is not suitable for dynamic removing:
1) Pass ArrayList<Fragment> data as parameter to PageAdapter
Then Adapter will look like this:
public class PageAdapter extends FragmentStatePagerAdapter {
private ArrayList<Fragment> data;
public PageAdapter(FragmentManager fm, ArrayList<Fragment> data) {
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
return data.get(position);
}
#Override
public CharSequence getPageTitle(int position) {
String title = "";
switch (position) {
case 0:
title = "Game"; // this is from a template, i have to
break; // return title dynamically
case 1:
title = "Movie";
break;
}
return title;
}
#Override
public int getCount() {
return data.size(); // the tabs number is a subject of change
} // i don't know it from the begining
}
to remove item you do in Activity\Fragment:
data.remove(fragmentId);
adapter.notifyDataSetChanged();
2) Recreate adapter every time you want to delete item. So you basically create new adapter with new data.
data.remove(fragmentId);
PageAdapter adapter = new PageAdapter(getFragmentManager(), data);
mViewPager.setAdapter(adapter);
Instead of using mTabLayout.setupWithViewPager(mViewPager); you can setup your tabs manually:
mTabLayout.addTab(mTabLayout.newTab().setText("Movie"));
mTabLayout.addTab(mTabLayout.newTab().setText("Game"));
mTabLayout.addTab(mTabLayout.newTab().setText("Audio"));
mTabLayout.setOnTabSelectedListener(this);
Removing is also easy: removeTabAt(int position) or removeTab(Tab tab)
Here I have found some better solution to remove all the views / fragments from the current context.
Here I have used TabLayout and ViewPage within Fragment.
So we need to clear tabs from TabLayout, views from ViewPage and fragments from FragmentManager.
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
FragmentManager fragmentManager = null;
public TabLayout tabLayout;
public ViewPager viewPager;
public ViewPagerAdapter(FragmentManager manager, TabLayout tabLayout, ViewPager pager) {
super(manager);
this.fragmentManager= manager;
this.tabLayout = tabLayout;
this.viewPager= pager;
}
public void removeAll() {
tabLayout.removeAllTabs();
viewPager.removeAllViewsInLayout();
viewPager.removeAllViews();
viewPager.setAdapter(null);
fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
if (manager.getFragments() != null) {
manager.getFragments().clear();
}
viewPager.setAdapter(adapterPage);
viewPager.invalidate();
viewPager.requestLayout();
mFragmentList.clear();
mFragmentTitleList.clear();
}