PagerSlidingTabStrip - add a new tab at runtime

I use PagerSlidingTabStrip to display 3 tabs, each of which contains a list view.

I have a scenario where I need to add a new tab at runtime, say when scrolling to update. I need to add a new tab to the left end.

Below my code will add a new tab:

pagerAdapter.TABS_COUNT = 4; //global value to change the tabs count
pagerAdapter.notifyDataSetChanged();
pagerSlidingTabStrip.setViewPager(mPager);

but several times the contents of one of the tabs becomes empty. listview does not scroll.

What is the best way to achieve this?

+4
source share
1 answer

, , , , https://github.com/jacktech24/pager-sliding-strip-example

-, , , , .. mTabs :

mTabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);

private class TestAdapter extends FragmentPagerAdapter {

        private ArrayList<String> tabs = new ArrayList<>();

        public TestAdapter(FragmentManager supportFragmentManager) {
            super(supportFragmentManager);
        }

        @Override
        public Fragment getItem(int position) {
            Fragment frag = new ExampleFragment();
            Bundle bundle = new Bundle();
            bundle.putString("title", (String) getPageTitle(position));
            frag.setArguments(bundle);
            return frag;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabs.get(position);
        }

        @Override
        public int getCount() {
            return tabs.size();
        }

        public void addTab(String tab) {
            tabs.add(tab);
            notifyDataSetChanged();
            mTabs.notifyDataSetChanged();
        }

        public void removeTab(int position) {
            tabs.remove(position);
            notifyDataSetChanged();
            mTabs.notifyDataSetChanged();
        }

    }

, :

    //mAdapter is instance of your adapter
    mAdapter.addTab("test 1");
    mAdapter.addTab("test 2");
    mAdapter.addTab("test 3");


    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mAdapter.addTab("test "+(mAdapter.getCount()+1));
        }
    });
0

Source: https://habr.com/ru/post/1611766/


All Articles