Search code examples
androidandroid-xmlandroid-tablayout

How to create a tab view (category) similar to instagram's explore tab


What i'm looking for is creating tab layout that can expand and collapse it's height when scrolling the content below. If anyone has any idea about how we can achieve it than it will be really helpful.

When Expanded It looks like this

When Collapsed It looks like this


Solution

  • As no answer was posted and I found the solution to these I'm posting the solution as an answer to this question.

    So, here is what I have done.

    I have taken two recyclerViews

    1. For Showing Category (horizontal Scrolling) (id = rvCategoryList)
    2. For Showing Items of the category (Vertical Scrolling) (id = rvItemList)

    Now have taken two variable for keeping the track of the last scroll and created a method to set the height of the rvCategoryList

    var lastY: Int = 0
    var counter = 0
    private fun setCategoryViewHeight(dy: Int) {
        val params = rvCategoryList.layoutParams
        if ((dy > 0 && lastY >= 0) || (dy < 0 && lastY <= 0)) {
            counter = 0
            params.height = params.height - dy
            if (dy > 0) {
                if (params.height < rvHeight / 1.7) {
                    params.height = (rvHeight / 1.7).toInt()
                }
            } else {
                if (params.height > rvHeight) {
                    params.height = rvHeight
                }
            }
            rvCategoryList.layoutParams = params
            lastY = dy
        } else {
            counter++
            if (counter > 2) {
                counter = 0
                lastY = 0
            }
        }
    }
    

    And Have applied OnScrollListener on the rvItemList as below.

    rvItemList.clearOnScrollListeners()
    rvItemList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            lastY = 0 //As the scroll state has been changed reinitializing the lastY variable.
        }
    
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            setCategoryViewHeight(dy) //Setting height everytime.
        }
    })
    

    I hope this will help someone who wants to create a similar view.