如何使选项卡下的选择器滚动到所选选项卡?

时间:2018-09-20 05:10:14

标签: android android-studio android-tablayout

tablayout with scroll

我想将选择器(粉红色的线)滚动到下一个选项卡(填充时)。我的片段正在滚动,但是选择器无法滚动。有人可以帮忙吗?

MainActivity.java

//Adding the tabs using addTab() method
    tabLayout.addTab(tabLayout.newTab().setText("On Reserved"));
    tabLayout.addTab(tabLayout.newTab().setText("On Fill-up"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

activity_main.java

<!-- our tablayout to display tabs  -->
<android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

<!-- View pager to swipe views -->
<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"></android.support.v4.view.ViewPager>

4 个答案:

答案 0 :(得分:5)

PagerAdapter pagerAdapter = new PagerAdapter(getChildFragmentManager());
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(mBinder.viewPager);//This line is important to make tab scrollable with viewpager and it should be after set adapter to viewpager

答案 1 :(得分:1)

尝试此解决方案

TabTextColor设置选项卡标题的颜色,在此处传递ColorStateList可使选项卡在不同情况下(例如选中,活动,非活动等)更改颜色。TabIndicatorColor设置选项卡下方的独立颜色。

tabLayout.setTabTextColors(ContextCompat.getColorStateList(this, R.drawable.tab_selector));
tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.indicator));

希望这对您有用。

答案 2 :(得分:1)

您必须像下面的代码一样在tablayout中分配viewpager

// listener for tablayout when you select tab for change view
tabLayout.setOnTabSelectedListener(this);
 // assign tablayout in viewpager
 viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

这是当您点击选项卡然后更改viewpager时的替代方法

@Override
public void onTabSelected(TabLayout.Tab tab) {
    viewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {

}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}

答案 3 :(得分:0)

当您也没有将viewpager设置为tablayout时,就会发生此问题,反之亦然。因此,请在代码中添加以下行...

PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(),nooftabs); viewpager.setAdapter(pagerAdapter);

tabLayout.setupWithViewPager(viewpager,true);

希望这可能对您有帮助