Search code examples
javaandroidandroidxandroid-tablayoutmaterial-components

TabLayout migration to AndroidX


I've migrated my Android App into AndroidX using refactor->migrate to AndroidX. Also fixed the ones that needed to be fixed manually. The only problem left is the TabLayout.

Previously, before AndroidX migration, I'm using this code:

    @Override
    public void setOnTabSelectedListener(OnTabSelectedListener onTabSelectedListener) {
        ......
        super.setOnTabSelectedListener(onTabSelectedListener);
    }

    @Override
    void selectTab(Tab tab) {
        ........
        super.selectTab(tab);
    }

But with AndroidX, when building I'm having this error: method does not override or implement a method from a supertype

and

selectTab(com.google.android.material.tabs.TabLayout.Tab) is not public. Cannot accessed from outside package..

How can I correctly migrate this to AndroidX?

Edit: forgot to mention that I have my own Tab class and I'm just extending the TabLayout. I've override the selectTab since I wan't to do something on it before calling the parent selectTab(). In AndroidX, the selectTab is not public anymore, so how can I override it to do something first?

Working code before AndroidX

@Override
void selectTab(Tab tab) {
   //if condition met, return;
  super.selectTab(tab);
}

Solution

  • You can use the selectTab method:

    TabLayout tabLayout = findViewById(R.id.tab_layout);
    tabLayout.selectTab(tabLayout.getTabAt(index));
    

    About the listener you can use the addOnTabSelectedListener

    tabLayout.addOnTabSelectedListener(OnTabSelectedListener);
    

    If you are using a custom TabLayout just use:

    @Override
    public void selectTab(@Nullable Tab tab) {
        //your code....
        super.selectTab(tab);
    }