如何以编程方式滚动tablayout - Android

问题描述 投票:19回答:13

我使用tablayout创建了30个可滚动的选项卡。

因此,前三个选项卡在屏幕上可见,其余部分是不可见的,可以使用滑动手势滚动。

问题是当我以编程方式选择最后一个选项卡但它不可见时(选项卡布局不会滚动到最后一个选项卡)。

如何使tablayout滚动到最后一个标签?

android android-tabs android-tablayout android-scrollable-tabs
13个回答
47
投票

我找到了解决方案。

首先,我找到了tablayout的宽度并将其x位置滚动到宽度,然后调用最后一个tab的select()方法。

它工作正常。

下面是代码。

mTabLayout.setScrollX(mTabLayout.getWidth());
mTabLayout.getTabAt(lastTabIndex).select();

更新:

如果上面没有工作,你也可以使用下面的代码,它也工作正常。

new Handler().postDelayed(
        new Runnable() {
            @Override public void run() {
                mTabLayout.getTabAt(TAB_NUMBER).select();
            }
        }, 100);

0
投票

我想知道这个答案是否具有相关性,因为它来得很晚。我实际上使用Xamarin在C#中实现了它。

tabs.GetChildAt(0).Selected = true;
 viewPager.SetCurrentItem(0, true);

0
投票

如果你的TabLayoutViewPager一起使用,这很常见,只需在你的Activity中的onCreate()方法中添加以下内容:

tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout);

您的某些选项卡未显示表示tabMode属性设置为app:tabMode="scrollable"


0
投票
tab = tabLayout.getSelectedTabPosition();
            tab++;
            TabLayout.Tab tabs = tabLayout.getTabAt(tab);
            if (tabs != null) {
                tabs.select();
            }
            else {
                tabLayout.getTabAt(0).select();
            }

如果你想要点击事件的下一个标签,那么使用这个代码完美的工作


0
投票

下面的代码片段适合我

class TriggerOnceListener(private val v: View, private val block: () -> Unit) : ViewTreeObserver.OnPreDrawListener {
    override fun onPreDraw(): Boolean {
        block()
        v.viewTreeObserver.removeOnPreDrawListener(this)
        return true
    }
}

fun onCreate() {
    val position = ***The tab position you want to scroll to, 29 for your case here***
    tabLayout.let { it.viewTreeObserver.addOnPreDrawListener(TriggerOnceListener(it)
    { it.setScrollPosition(position, 0f, true) } ) }
}

我潜入Tab.select(),发现Android使用Tablayout.setScrollPosition()来做这个滚动。在onCreate()中,小部件尚未测量,您需要推迟调用直到布局完成。


5
投票

我找到了这个解决方案:

    TabLayout tabLayout = activity.getTabLayout();
    tabLayout.setSmoothScrollingEnabled(true);
    tabLayout.setScrollPosition(targetChannelPosition, 0f, true);

此外,如果您收到此错误:“只有创建视图层次结构的原始线程可以触摸其视图。”,您可以使用此代码,以便在Ui线程上运行:

    // find a way to get the activity containing the tab layout
    TabLayout tabLayout = activity.getTabLayout();
    activity.runOnUiThread(new Runnable()
    {
        @Override
        public void run()
        {
            TabLayout.Tab tab = tabLayout.getTabAt(targetChannelPosition);
            tab.select();
        }
    });

4
投票

在自定义tablayout中编写此方法(您自己的布局扩展了tablayout)。因此,将来您可以在需要实例化代码重复时使用此方法

public void selectTabAt(int tabIndex) {
        if (tabIndex >= 0 && tabIndex < getTabCount() && getSelectedTabPosition() != tabIndex) {
            final Tab currentTab = getTabAt(tabIndex);
            if (currentTab != null) {
                this.post(new Runnable() {
                    @Override
                    public void run() {
                        currentTab.select();
                    }
                });
            }
        }
    }

如果您不想使用自定义布局。你可以这样做

final Tab currentTab = mTabLayout.getTabAt(tabIndex);
if(currentTab != null){
     mTabLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        currentTab.select();
                    }
                });
}

2
投票

上面的答案是行不通的,因为首先如同agirardello提到你不应该使用mTabLayout.getWidth(),因为它不会返回我们需要的东西(这是你要滚动到的孩子的位置),并且更新的解决方案并不总是有效,因为TabLayout中的一个错误(报告here),但解决方法很简单。

tabLayout上的选项卡不是TabLayout的直接子项,因此我们需要更深入地使用

((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(YOUR_DESIRED_TAB_INDEX).getRight()

tabLayout的唯一孩子是TabLayout.SlidingTabStrip,也是ViewGroupgetRight()将给我们所需的标签视图的最正确的位置。因此滚动到那个位置将给我们想要的东西。这是一个完整的代码:

int right = ((ViewGroup) mTabLayout.getChildAt(0)).getChildAt(4).getRight();
mTabLayout.scrollTo(right,0);
mTabLayout.getTabAt(4).select();

注意:确保在布局被淹没后调用这些方法(如onResume而不是onCreate)

希望这可以帮助。


1
投票

要选择最后一个选项卡,请使用tabLayout.getTabAt(X).select();其中X是最后一个标签索引


1
投票

您是否在TabLayout之前调用tab.select()并且其子项实际上已被测量和绘制?如果是这样,你的TabLayout将不会使用tab.select()(或Kayvan N的scrollTo()建议)为选择设置动画。使用处理程序可能会起作用,但这不是一个理想的解决方案。

如果布局尚未布局,则在布局过程完成后,ViewTreeObserver将允许您移动到所选选项卡。

private void scrollToTabAfterLayout(final int tabIndex) {
    if (getView() != null) {
        final ViewTreeObserver observer = mTabLayout.getViewTreeObserver();

        if (observer.isAlive()) {
            observer.dispatchOnGlobalLayout(); // In case a previous call is waiting when this call is made
            observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        observer.removeOnGlobalLayoutListener(this);
                    } else {
                        //noinspection deprecation
                        observer.removeGlobalOnLayoutListener(this);
                    }

                    mTabLayout.getTabAt(tabIndex).select();

                }
            });
        }
    }
}

如果您有任何建议,请评论。


1
投票
new Handler().postDelayed(
    new Runnable() {
        @Override public void run() {
            mTabLayout.getTabAt(TAB_NUMBER).select();
        }
    }, 100);

0
投票

viewpager.setItem(position)还应该设置标签的位置


0
投票

这个解决方案对我有用。我的情况有点不同;在我的例子中,我使用带有ViewPager的TabLayout并添加更多视图并调用notifyDataSetChange()。

解决方案是在TabLayout的观察者上设置回调,并在子项实际添加到TabLayout时滚动。这是我的例子:

/**
    Keep in mind this is how I set my TabLayout up...

    PagerAdapter pagerAdapter = new PagerAdapter(...);
    ViewPager pager = (ViewPager)findViewById(...);
    pager.setAdapter(pagerAdapter);

    TabLayout tabLayout = (TabLayout)findViewById(...);
    tabLayout.setupWithViewPager(pager);
*/
public void loadTabs(String[] topics) {
    animateTabsOpen(); // Irrelevant to solution

    // Removes fragments from ViewPager
    pagerAdapter.clear();

    // Adds new fragments to ViewPager
    for (String t : topics)
         pagerAdapter.append(t, new TestFragment());

    // Since we need observer callback to still animate tabs when we
    // scroll, it is essential to keep track of the state. Declare this
    // as a global variable
    scrollToFirst = true;

    // Alerts ViewPager data has been changed
    pagerAdapter.notifyOnDataSetChanged();

    // Scroll to the beginning (or any position you need) in TabLayout
    // using its observer callbacks
    tabs.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            /**
                 We use onGlobalLayout() callback because anytime a tab
                 is added or removed the TabLayout triggers this; therefore,
                 we use it to scroll to the desired position we want. In my
                 case I wanted to scroll to the beginning position, but this
                 can easily be modified to scroll to any position.
             */
            if (scrollToFirst) {
                tabs.getTabAt(0).select();
                tabs.scrollTo(0, 0);
                scrollToFirst = false;
            }
        }
    });
}

如果你需要它,这是我的PagerAdapter的代码lol:

public class PagerAdapter extends FragmentStatePagerAdapter {
    private List<Fragment> fragments;
    private List<String> titles;


    public PagerAdapter(FragmentManager fm) {
        super(fm);
        this.fragments = new ArrayList<>();
        this.titles = new ArrayList<>();
    }

    /**
     * Adds an adapter item (title and fragment) and
     * doesn't notify that data has changed.
     *
     * NOTE: Remember to call notifyDataSetChanged()!
     * @param title Fragment title
     * @param frag Fragment
     * @return This
     */
    public PagerAdapter append(String title, Fragment frag) {
        this.titles.add(title);
        this.fragments.add(frag);
        return this;
    }

    /**
     * Clears all adapter items and doesn't notify that data
     * has changed.
     *
     * NOTE: Rememeber to call notifyDataSetChanged()!
     * @return This
     */
    public PagerAdapter clear() {
        this.titles.clear();
        this.fragments.clear();
        return this;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Override
    public int getItemPosition(Object object) {
        int position = fragments.indexOf(object);
        return (position >= 0) ? position : POSITION_NONE;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.