Devesh Agrawal
Devesh Agrawal

Reputation: 9212

How to get tab click event in activity on TabLayout android

This is the implementation of the onCreate method in my activity. I need to create the tabs dynamically. For simplicity, I made 2 tabs.

public class ActivityProductList extends AppCompatActivity {

    private android.support.v7.widget.SearchView searchView = null;
    private RecyclerView recyclerView;
    MyAdapter adapter;
    List<ParentListItem> parentListItems = new ArrayList<>();
    List<ParentListItem> originalProductList = new ArrayList<>();
    String query = null;
    int categoryId = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_products_final);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("PRODUCTS");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        //ViewPager viewPager = (ViewPager) findViewById(R.id.pager);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        //setupViewPager(viewPager);
        //tabLayout.setupWithViewPager(viewPager);
        //viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        searchView = (android.support.v7.widget.SearchView) findViewById(R.id.searchView);
        searchView.setIconified(false);
        searchView.onActionViewExpanded();
        searchView.clearFocus();
        searchView.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (adapter != null)
                    filterData(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String query) {
                if (adapter != null)
                    filterData(query);
                return false;
            }
        });

    }
}

I want to change the EditText value on clicking on a tab. That EditText is in the same activity.

How do I get Tab click event in Activity?

Upvotes: 39

Views: 66604

Answers (8)

Jonas.S.
Jonas.S.

Reputation: 317

private fun setupTabLayout() {

    tabLayout?.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {

        override fun onTabSelected(tab: TabLayout.Tab?) {

            when (tab?.position){
                0 -> println(0)
                1 -> println(1)
                2 -> println(2)
            }
        }

        override fun onTabReselected(tab: TabLayout.Tab?) {
            // Write code to handle tab reselect
        }

        override fun onTabUnselected(tab: TabLayout.Tab?) {
            // Write code to handle tab reselect
        }
    })
}

Upvotes: 0

HT__
HT__

Reputation: 11

as mentioned @dgngulcan, onTabSelected will also be called as a result of swiping, not only tapping the tab.

we can use the view from the tab directly as parameter

here I combine tabs with a view pager, and add a click listener, if clicked it will call a certain function

tabLayout = binding.tabLayout
    val tabAll = tabLayout.newTab().setText("All")
    val tabFavourite = tabLayout.newTab().setText("Favourite")
    tabLayout.addTab(tabAll)
    tabLayout.addTab(tabFavourite)
    tabLayout.setSelectedTabIndicatorColor(Color.WHITE)

    tabAll.view.setOnClickListener {
        if(viewPager.currentItem==0)
            allCoinsListFragment.scrollToTop()
        else
        viewPager.currentItem = 0
    }
    tabFavourite.view.setOnClickListener {
        if(viewPager.currentItem==1)
            favouriteCoinsListFragment.scrollToTop()
        else
        viewPager.currentItem = 1
    }

Upvotes: 1

HAZEEM JOONUS
HAZEEM JOONUS

Reputation: 583

In Java,

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                Toast.makeText(this, "position : "+position, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

Upvotes: 1

Vinh Nguyen
Vinh Nguyen

Reputation: 21

this could help somebody

TabLayoutMediator(tabLayout, viewPager) { tab, position ->
                tab.text = tabTitle[position]
                if (position == YOUR_TAB_POSITION) {
                    tab.view.isClickable = false
                    tab.view.setOnTouchListener { view, motionEvent ->
                        if(Your_condition){ 
                            false
                        } else {
                            view.performClick()
                        }
                    }
                } else {
                    tab.view.isClickable = true
                }
            }.attach()

The reason I'm not using onTouch for click to switching normal tab because it will broken slide animation of TabLayout, so I'm still using clickable = true

Upvotes: 2

hakim
hakim

Reputation: 3909

If what you want is when a tab is clicked and not each time a tab is selected, you can use custom view for each tab and then handle click on respective view like this:

for (int i = 0; i < tabLayout.getTabCount(); i++) {
    final TabLayout.Tab tab = tabLayout.getTabAt(i);
    final View tabView = LayoutInflater.from(this).inflate(
            R.layout.item_tab, (ViewGroup) tab.getCustomView(), false);
    tabLayout.setCustomView(tabView);

    final TextView customView = (TextView) tab.getCustomView();
    customView.setText(mAdapter.getPageTitle(i));
    final int index = i;
    customView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (tabLayout.getSelectedTabPosition() == index) {
                // change edittext value
            } else {
                tab.select();
            }
        }
    });
}

Upvotes: 3

Shashank Udupa
Shashank Udupa

Reputation: 2223

You can use the onTabSelected listener to achieve that.

tabLayout.addOnTabSelectedListener(new OnTabSelectedListener() {
        @Override
        public void onTabSelected(Tab tab) {
             switch(tab.getPosition()) {
                 case 0:
                  ....
             }
        }

P.S. setOnTabSelectedListener is deprecated, please use addOnTabSelectedListener instead.

Upvotes: 62

Zohab Ali
Zohab Ali

Reputation: 9574

You can use the onTabSelected listener in Kotlin like this

tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })

Upvotes: 31

Mehdi Dehghani
Mehdi Dehghani

Reputation: 11601

Here is Xamarin.Android/C# port of Shashank Udupa's answer, that works for me:

First you should implement IOnTabSelectedListener interface like below:

public class MyOnTabSelectedListener : Java.Lang.Object, TabLayout.IOnTabSelectedListener
{
    Activity _activity;

    public MyOnTabSelectedListener(Activity activity)
    {
        _activity = activity;
    }

    public void OnTabReselected(TabLayout.Tab tab)
    {
    }

    public void OnTabSelected(TabLayout.Tab tab)
    {
        switch (tab.Position)
        {
            case 0:
                // your logic goes here!
                break;

            // ...
        }
    }

    public void OnTabUnselected(TabLayout.Tab tab)
    {
    }
}

Then use above class like this:

tabLayout.AddOnTabSelectedListener(new MyOnTabSelectedListener(this));

Upvotes: 0

Related Questions