【问题标题】:Update TabLayout titles更新 TabLayout 标题
【发布时间】:2018-08-07 22:55:16
【问题描述】:

我有一个TabLayout(来自设计库),它通过FragmentPagerAdapter 填充了2 个片段(它们都包含一个项目列表)。

这两个列表是相互关联的:它们都包含一个人,一个人在哪个列表中,决定了他/她是否被提名。 您可以将成员从一个列表滑动到另一个列表,反之亦然。

问题

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

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

这个方法所做的就是removeAllTabs,然后循环遍历FragmentPagerAdapter 拥有的那些,将它们添加为新的。

这适用于标题,但效率不高,但最重要的是:它会强制第一个选项卡再次成为选定项目,从第二个选项卡滑动时这不是一个很好的体验。

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

我也尝试过

mAdapter.notifyDataSetChanged();
tabLayout.invalidate();

没有效果。

【问题讨论】:

  • 您可以尝试将setCurrentItem()发布到处理程序中或直接发布到ViewPager,或者如果您知道要更改的标题索引,请使用tabLayout.getTabAt(index)
  • 哇,不知道我怎么错过了getTabAt(index) method

标签: android android-tablayout


【解决方案1】:

这就是我的做法,我有一个要求,我需要每次都为标签标题设置一些计数。

我为标签标题使用了自定义布局。这是我的 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 方法来更新选项卡标题,但它不会更新标题,它会在标题末尾附加新文本。所以我从选项卡布局中获取视图并使用它来更新和读取选项卡值。

希望这会对您有所帮助。

【讨论】:

    猜你喜欢
    • 2016-01-17
    • 2017-01-22
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多