Search code examples
androidandroid-viewpagerandroid-tablayout

How to detect a click on every single tab in tablayout?


I have a viewpager with undetermined pages, because the user can add pages too. Thats okay, but I have no idea how to make it possible, that my user could delete those pages. I have tried to implement a long click listener on every tab with the code below, but it is not working.

Then how to detect which one tab is clicked?

for (tabCounter = 0; tabCounter < DataOfPages.size(); tabCounter++) {
        tabLayout.getTabAt(tabCounter).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                dataSource.open();
                dataSource.deleteById(tabCounter);
                dataSource.close();

                setupViewPager(viewPager);
                return true;
            }
        });
    }

Solution

  • Implementation of LongClick listener to each TAB:

    LinearLayout tabStrip = (LinearLayout) tabLayout.getChildAt(0);
    
    for (int i = 0; i < tabStrip.getChildCount(); i++) {
    
        // Set LongClick listener to each Tab        
        tabStrip.getChildAt(i).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
    
                Toast.makeText(getApplicationContext(), "Tab clicked" , Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }
    

    Hope this will help~