Disable TabLayout

前端 未结 11 1820
时光说笑
时光说笑 2020-11-29 02:49

I\'m using the new class provided by the design library : TabLayout. And I want in specific cases that the one I\'m using can\'t change tab anymore.

I manage to disa

相关标签:
11条回答
  • 2020-11-29 03:20

    check my answer here Disable Tabs in TabLayout

    You can for loop tab and use this function to disable all tab

    0 讨论(0)
  • 2020-11-29 03:22

    Based on Michele's Accepted Answer, to disable click for a single tab in Kotlin:

    Inside the tabs-containing activity:

    val tabs: TabLayout = findViewById(R.id.tabs)
    ...
    
    (tabs.getChildAt(0) as LinearLayout).getChildAt(desiredTabPositionHere).isClickable = false
    

    Inside the fragments (tabs):

    (requireActivity().tabs.getChildAt(0) as LinearLayout).getChildAt(desiredTabPositionHere).isClickable = false
    

    You can turn the click function on and off (by setting true or false). With the same method, it is also possible to modify visibility, alpha, backgroundColor etc.

    0 讨论(0)
  • It's also possible to avoid child clicks by extending TabLayout class and intercepting all the touch events.

    class NonTouchableTabLayout : TabLayout {
    
        constructor(context: Context) : super(context)
        constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    
        override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
            return true
        }
    }
    

    If you want to enable clicks again just return false on onInterceptTouchEvent method.

    0 讨论(0)
  • 2020-11-29 03:33

    Based on this excellent solution , if someone needs it in Kotlin :

      val tabStrip = mTabLayout.getChildAt(0) as LinearLayout
        for (i in 0..tabStrip.childCount) {
            tabStrip.getChildAt(i).setOnTouchListener(object : View.OnTouchListener{
                override fun onTouch(p0: View?, p1: MotionEvent?): Boolean {
                    return true
                }
            })
        }
    

    Or a more elegant solution with lambdas

    mTabLayout.setOnTouchListener {v: View, m: MotionEvent ->
            true
     }
    
    0 讨论(0)
  • 2020-11-29 03:34

    A good trick you can use :

    create a frame layout that cover the view(s) you want to protect from a click like the following :

    <FrameLayout
        android:clickable="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    

    This code will create and empty/transparent view on top of your view. The android:clickable="true" will intercept the click and prevent the click to go through the view !

    This hack can probably be optimized but its few lines of code to protect multiple view at the same time !

    0 讨论(0)
提交回复
热议问题