我遇到了 android TabLayout 的棘手问题
import android.support.design.widget.TabLayout;
当我选择左侧最前面的选项卡,然后向右滚动选项卡并选择右侧最前面的选项卡时,TabLayout 首先再次显示左侧选项卡,然后滚动到右侧的选定选项卡。这是我的设置代码
void setupTabs(ViewPager viewPager, TabLayout tabLayout) {
ProductsPagerAdapter adapter = new ProductsPagerAdapter(getChildFragmentManager(), rootCategory.getChildCategories());
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
setStartingSelection(viewPager, adapter);
}
private void setStartingSelection(ViewPager viewPager, ProductsPagerAdapter adapter) {
for(int i = 0 ; i < adapter.getCount(); i++){
String title = (String) adapter.getPageTitle(i);
if(title.equals(selectedCategory.getName())){
viewPager.setCurrentItem(i);
break;
}
}
}
和布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/toolbar_color"
app:navigationIcon="@drawable/ic_back_white"
app:title="@string/title_transport"
app:titleTextColor="@color/title_color"/>
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
app:tabTextColor="@color/white"
app:tabIndicatorColor="@color/tab_indicator"
app:tabGravity="fill"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="@android:color/white" />
</LinearLayout>
最佳答案
你可以试试这段代码
tabLayout.setupWithViewPager(viewPager);
// little hack to prevent unnecessary tab scrolling
tabLayout.clearOnTabSelectedListeners();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition(), false);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) { }
@Override
public void onTabReselected(TabLayout.Tab tab) { }
});
或者你也可以直接在最后一行这样做
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition(), false);
}
});
关于android - TabLayout 删除不必要的滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41891598/