动态添加标签到SlidingTabLayout(Android)

时间:2015-07-30 17:22:06

标签: android android-fragments tabs

我按照这些guidelines创建了带有片段的Sliding标签布局。问题是我想动态地向SlidingTabLayout添加一个标签。以下代码创建了一个片段,但它没有显示。如何将它附加到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();

这是我的ViewPagerAdapter类

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;
}

}

1 个答案:

答案 0 :(得分:0)

解决方案非常简单:) 您应该将此方法添加到“ViewPagerAdapter”并通过此

更改CharSequence
List<String> titles = new ArrayList<String>();

现在构造函数应该是:

public ViewPagerAdapter(FragmentManager fm, List<String> mTitles, int mNumbOfTabsumb) {
    super(fm);

    this.titles = mTitles;
    this.numbOfTabs = mNumbOfTabsumb;
}

添加到'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();
}

从您的活动或您调用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

请注意'ViewPagerAdapter'中的'getItem'方法,因为现在您要动态添加标签;)