【问题标题】:How can I disable click on TabLayout in Android如何在 Android 中禁用单击 TabLayout
【发布时间】:2016-10-15 00:57:32
【问题描述】:

我想在我的应用程序中使用TabLayout 以使用fragmentViewPager
但我想禁用点击TabLayoutfragment之间切换,只需滑动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;
        }
    });
}

我该如何解决这个问题?谢谢大家

【问题讨论】:

  • 设置android:clickable="false"
  • @TimCastelijns,不适合我
  • Disable TabLayout的可能重复

标签: android android-fragments


【解决方案1】:

您在 setupWithViewPager 之前访问选项卡,这就是您的代码无法正常工作的原因。所以先设置标签,然后设置touchlistener代码。

试试这个:

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;
            }
        });
    }

【讨论】:

    【解决方案2】:
    tabLayout.clearOnTabSelectedListeners();
    

    【讨论】:

    • 您好,欢迎来到 StackOverflow。请为您的答案添加一些解释,以便它对其他用户更有价值。见stackoverflow.com/help/how-to-answer
    • 如果您从 Android Material Components 中使用 TabLayout,它应该可以不受 API 24 限制。
    • 这不会禁用标签的点击。被点击的标签会被选中,但是这次点击不会通知 ViewPager。
    【解决方案3】:

    The above answer here,当您完成填充选项卡项或已在 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>
    

    该方法在调用时间上略有不同,您只需设置您的 tabitem 以在所有 viewpager 片段都已添加后禁用其点击。

    如果有人对此有更好的方法,请编辑我的答案

    【讨论】:

      【解决方案4】:

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

      声明活动

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

      禁用所有标签

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

      启用标签

      touchableList?.get(0)?.isEnabled = true
      

      【讨论】:

        【解决方案5】:

        这对我有用:

        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
        }
        

        【讨论】:

          【解决方案6】:

          无需使用线性布局,您只需将其添加到活动中即可:

          private void setUntouchableTab () {
              tablayout.setupWithViewPager(viewpager, true);
              tablayout.clearOnTabSelectedListeners();
              for (View v : tablayout.getTouchables()) {
                  v.setEnabled(false);
              }
          }
          

          【讨论】:

          • 应该是公认的答案:) 我在这里找到了更好更快的解决方案!谢谢
          • 这很好用,但我无法让 setEnabled(true) 重新启用点击。
          【解决方案7】:

          对于 ViewPager2(最低 v1.1.0),您可以在 TabLayoutMediator 中完成此操作。

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

          build.gradle:

          com.google.android.material:material:1.1.0-rc02
          

          【讨论】:

            猜你喜欢
            • 2017-05-19
            • 2012-10-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多