更新TabLayout标题

时间:2015-08-16 05:58:46

标签: android android-tablayout

我有TabLayout(来自设计资料库),其中包含2个片段(两者都包含项目列表),通过FragmentPagerAdapter

这两个名单彼此相关:他们共同拥有一个人,一个人在哪个名单中,决定他/她是否被提名。 您可以将成员从一个列表滑动到另一个列表,反之亦然。

问题

我想/需要在标签标题中显示一个计数(该特定列表中有多少人)。 很简单,我在getPageTitle中添加了一些代码,它运行正常。 在我更改列表之前,我需要告诉FragmentPagerAdapter再次更新其标题:它不会。

到目前为止,我找到的唯一解决方案是致电:mTabLayout.setTabsFromPagerAdapter(mAdapter);

所有这些方法都是removeAllTabs,然后遍历FragmentPagerAdapter所拥有的方法,将它们添加为新的方法。

这适用于标题,但不是非常有效,但最重要的是:它强制第一个标签再次成为所选项目,从第二个标签滑动时不是一个很好的体验。

我在mViewPager.setCurrentItem(int item)电话后尝试添加mTabLayout.setTabsFromPagerAdapter(mAdapter);,但这不起作用。

我也尝试过像

这样的事情
mAdapter.notifyDataSetChanged();
tabLayout.invalidate();

没有效果。

1 个答案:

答案 0 :(得分:0)

这是我的工作方式,我有一个要求,我每次都需要为标签标题设置一些计数。

我为标签标题使用了自定义布局。这是我的custom_tab布局

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/colorAccent"
    android:textSize="@dimen/tab_label" />

要设置标题第一次,我使用我的方法 setupTabTitle(“ TAB 1”,0);

private void setupTabTitle(String title,int pos) {
   TextView title = (TextView) LayoutInflater.from(this).
          inflate(R.layout.custom_tab, null);
   title .setText(title);
 // set icon
// title .setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_tab_favourite, 0, 0);
   tabLayout.getTabAt(pos).setCustomView(title);
}

下一次更新,我使用tabLayout.getTabAt()对象

public void updateCustomTabTitle(String title,int pos) {
    TextView tabTitle = (TextView) tabLayout.getTabAt(pos).getCustomView();
    tabTitle.setText(title);
}

这就是我如何调用updateCustomTabTitle方法

updateCustomTabTitle("My tab title to update",tabLayout.getSelectedTabPosition());

获取标签标题值

public String getCustomTabTitle(int pos) {
    TextView tabOne= (TextView) tabLayout.getTabAt(pos).getCustomView();
    return tabOne.getText().toString();
}

注释:首先,我尝试了setupTabTitle方法来更新选项卡标题,但它不会更新标题,它会在标题末尾添加新文本。这样我就可以从选项卡布局中获取视图,并使用它来更新和读取选项卡值。

希望这会对您有所帮助。

相关问题