如何在安卓系统中禁止点击TabLayout?

36 人关注

我想在我的应用程序中使用 TabLayout ,以使用 fragment ViewPager
但我想禁用点击 TabLayout 来切换 fragment just swipe to switch between fragmenst .
我写了下面的代码,但对我不起作用,当点击 TabLayout 的项目时,转到那个 fragment !

MainActivity XML。

<android.support.design.widget.CoordinatorLayout 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.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            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="?attr/colorPrimary"
                app:layout_scrollFlags="scroll|enterAlways"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:text="@string/app_namefull"
                    android:textSize="23sp" />
            </android.support.v7.widget.Toolbar>
            <android.support.design.widget.TabLayout
                android:id="@+id/tabs"
                android:layout_width="match_parent"
                android:layout_height="72dp"
                app:tabGravity="fill"
                app:tabIndicatorColor="@color/white"
                app:tabMode="fixed" />
        </android.support.design.widget.AppBarLayout>
        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />
    </android.support.design.widget.CoordinatorLayout>

MainActivity java:

public class Main_Page extends AppCompatActivity {
    private CollapsingToolbarLayout mCollapsingToolbarLayout;
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main__page);
        mCollapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout);
        //mCollapsingToolbarLayout.setTitle(getResources().getString(R.string.app_name));
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        LinearLayout tabStrip = ((LinearLayout)tabLayout.getChildAt(0));
        for(int i = 0; i < tabStrip.getChildCount(); i++) {
            tabStrip.getChildAt(i).setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return true;
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();
     * Adding custom view to tab
    private void setupTabIcons() {
        TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabOne.setText(R.string.free_fragment_title);
        tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_download_image, 0, 0);
        tabLayout.getTabAt(0).setCustomView(tabOne);
        TextView tabTwo = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabTwo.setText(R.string.paid_fragment_title);
        tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_paid_download_image, 0, 0);
        tabLayout.getTabAt(1).setCustomView(tabTwo);
        TextView tabThree = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
        tabThree.setText(R.string.pdf_fragment_title);
        tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_pdf_icon, 0, 0);
        tabLayout.getTabAt(2).setCustomView(tabThree);
     * Adding fragments to ViewPager
     * @param viewPager
    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFrag(new free_fragment(), "رایگان ها");
        adapter.addFrag(new paid_fragment(), "پرداختی ها");
        adapter.addFrag(new pdf_fragment(), "مقالات");
        viewPager.setAdapter(adapter);
    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();
        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        @Override
        public int getCount() {
            return mFragmentList.size();
        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);

点击TabLayout进行禁用。我使用这个代码。

LinearLayout tabStrip = ((LinearLayout)tabLayout.getChildAt(0));
for(int i = 0; i < tabStrip.getChildCount(); i++) {
    tabStrip.getChildAt(i).setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;

How can I solve this problem? Thanks all <3

3 个评论
Tim
set android:clickable="false"
@TimCastelijns,不工作的我
可能是重复的 禁用TabLayout
android
android-fragments
Mohammad Nouri
Mohammad Nouri
发布于 2016-06-14
7 个回答
Manish Jain
Manish Jain
发布于 2018-12-18
已采纳
0 人赞同

你在setupWithViewPager之前访问了tab,这就是为什么你的代码不工作。所以先设置标签,然后再设置Touchlistener代码。

Try this:

tabLayout.setupWithViewPager(viewPager);
    setupTabIcons();
LinearLayout tabStrip = ((LinearLayout)mTabLayout.getChildAt(0));
    for(int i = 0; i < tabStrip.getChildCount(); i++) {
        tabStrip.getChildAt(i).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
    
l33t
l33t
发布于 2018-12-18
0 人赞同

For 查看页面2 (最低v1.1.0)你可以在 TabLayoutMediator 中完成这个任务。

new TabLayoutMediator(tabLayout, pager,
        (tab, position) -> {
            tab.view.setClickable(false);
).attach();

And in build.gradle:

com.google.android.material:material:1.1.0-rc02
    
我想补充的是,我正在使用数据绑定,这样做之后,我试图重新启用它们,但 binding.tablayout.touchables.forEach { it.isClickable = true } 却不起作用。解决办法是对每个标签使用 binding.tablayout.getTabAt(0)?.view?.isClickable = true
Arul Pandian
Arul Pandian
发布于 2018-12-18
0 人赞同

可触摸的数组列表将解决这个问题。

var touchableList: ArrayList<View>? = ArrayList()

禁用所有标签

touchableList = tabLayout?.touchables
touchableList?.forEach { it.isEnabled = false }

启用该标签

touchableList?.get(0)?.isEnabled = true
    
dreinoso
dreinoso
发布于 2018-12-18
0 人赞同

不需要使用线性布局,你可以直接在活动上添加这个。

private void setUntouchableTab () {
    tablayout.setupWithViewPager(viewpager, true);
    tablayout.clearOnTabSelectedListeners();
    for (View v : tablayout.getTouchables()) {
        v.setEnabled(false);
    
应该是公认的答案:)我在这里找到了更好、更快的解决方案!谢谢
这很好用,但我无法让setEnabled(true)重新启用点击。
Lena
Lena
发布于 2018-12-18
0 人赞同
tabLayout.clearOnTabSelectedListeners();
    
wmk
你好,欢迎来到StackOverflow。请在您的答案中加入一些解释,以便对其他用户更有价值。请看 stackoverflow.com/help/how-to-answer
如果你唱的是Android Material Components的TabLayout,它应该可以不受API 24的限制。
这不会使标签的点击失效。被点击的标签将被选中,但ViewPager不会被这个点击所通知。
Dionis Beqiraj
Dionis Beqiraj
发布于 2018-12-18
0 人赞同

这就是对我有用的方法。

class LockableTabLayout : TabLayout {
    var swipeable: Boolean = true
    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    override fun onInterceptTouchEvent(event: MotionEvent): Boolean = !swipeable
    
mochadwi
mochadwi
发布于 2018-12-18
0 人赞同

这里的上述答案 当你已经完成填充你的标签项或已经在xmls上定义了标签项时,禁止点击标签项。

        <android.support.design.widget.TabLayout
            android:id="@+id/tabla_quiz_navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <android.support.design.widget.TabItem
                android:layout_width="wrap_content"
                android:text="1"
                android:layout_height="wrap_content"/>
            <android.support.design.widget.TabItem
                android:layout_width="wrap_content"
                android:text="2"
                android:layout_height="wrap_content"/>
            <android.support.design.widget.TabItem
                android:layout_width="wrap_content"
                android:text="3"
                android:layout_height="wrap_content"/>
        </android.support.design.widget.TabLayout>

但是,如果你有不同的情况,当使用Observable数据或动态tabitem时,例如。

        // QuizFragment.kt
        quizListLive.observe(this@QuizFragment, Observer { quizList ->
            quizList?.takeIf { list -> list.isNotEmpty() }?.let {
                // this is where new fragment added
                it.forEachIndexed { j, quiz ->
                    mViewPagerAdapter?.addFragment(
                            fragment = QuizFragmentSub.newInstance(quiz = quiz),
                            title = (j + 1).toString()
                // notify the viewpager, I'm using kotlin extension to call widget id
                vp_quiz_content.adapter?.notifyDataSetChanged()
                // then, childCount will have size > 0
                // disable tablayout click
                val tabStrip = tabla_quiz_navigation.getChildAt(0) as LinearLayout
                for (i in 0 until tabStrip.childCount) {
                    tabStrip.getChildAt(i).setOnTouchListener { _, _ -> true }
        // quiz_fragment.xml
        <android.support.design.widget.TabLayout
            android:id="@+id/tabla_quiz_navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"></android.support.design.widget.TabLayout>