Add OnLongClickListener on android support TabLayout | TabLayout.Tab
Asked Answered
P

1

6

I am using the TabLayout found in the Service library. I have tried to add an OnLongClickListener when long-clicking on a tab. It has been impossible for me. I have even been trying to "hack" it by using childViews:

View tabLayoutChild = tabLayout.getChildAt(0);
    ViewGroup group = (ViewGroup) tabLayoutChild;
    group.getChildAt(0).setOnLongClickListener(this);

Doesn't work and does NOT look pretty. It is all very handy except for the longClick I want to implement.

My small snippet of code

pagerAdapter = new CustomFragmentPagerAdapter(getSupportFragmentManager());
    pagerView.setAdapter(pagerAdapter);
    tabLayout.setupWithViewPager(pagerView);

The tablayout has a method setOnLongClickListener() but what I can tell, it does nothing.

How can I implement a LongClickListener for a tab in a tablayout?

Pedropedrotti answered 27/10, 2015 at 11:49 Comment(0)
E
9

You can do

mTabLayout.getChildAt(0).setOnLongClickListener

to set it on the tab host, but this mean that it only triggers when you tap the space in the TabHost that doesn't contain a tab (background?).

The tabs itself reside in a SlidingTabStrip which extends LinearLayoutand we can use it to get to each tab. So we set the long press listener per tab like this:

LinearLayout tabStrip = (LinearLayout) mTabLayout.getChildAt(0);
for (int i = 0; i < tabStrip.getChildCount(); i++) {
    tabStrip.getChildAt(i).setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            return false;
        }
    });
}
Ethbun answered 24/1, 2016 at 23:5 Comment(1)
If your tablayout is dynamically filled (the tabs themselves), make sure to call this only after filling it.Surrey

© 2022 - 2024 — McMap. All rights reserved.