Change image on Tab in TabLayout when Selected

后端 未结 3 1190
北荒
北荒 2021-01-05 02:11

I am using Design TabLayout,



        
3条回答
  •  既然无缘
    2021-01-05 02:49

    add the setOnTabSelectedListener to the tabLayout object

    i named mine navigation

    navigation.setOnTabSelectedListener(
                new TabLayout.ViewPagerOnTabSelectedListener(mainView) {
    
                    @Override
                    public void onTabSelected(TabLayout.Tab tab) {
                        super.onTabSelected(tab);
    
                        // 1. get the custom View you've added
                        View tabView = tab.getCustomView();
    
                        // get inflated children Views the icon and the label by their id
                        TextView tab_label = (TextView) tabView.findViewById(R.id.nav_label);
                        ImageView tab_icon = (ImageView) tabView.findViewById(R.id.nav_icon);
    
                        // change the label color, by getting the color resource value
                        tab_label.setTextColor(getResources().getColor(R.color.active_color));
                        // change the image Resource
                        // i defined all icons in an array ordered in order of tabs appearances
                        // call tab.getPosition() to get active tab index.
                        tab_icon.setImageResource(navIconsActive[tab.getPosition()]);
                    }
    
                    // do as the above the opposite way to reset tab when state is changed 
                    // as it not the active one any more
                    @Override
                    public void onTabUnselected(TabLayout.Tab tab) {
                        super.onTabUnselected(tab);
                        View tabView = tab.getCustomView();
                        TextView tab_label = (TextView) tabView.findViewById(R.id.nav_label);
                        ImageView tab_icon = (ImageView) tabView.findViewById(R.id.nav_icon);
    
                        // back to the black color
                        tab_label.setTextColor(getResources().getColor(R.color.dark_grey));
                        // and the icon resouce to the old black image 
                        // also via array that holds the icon resources in order 
                        // and get the one of this tab's position
                        tab_icon.setImageResource(navIcons[tab.getPosition()]);
                    }
    
                    @Override
                    public void onTabReselected(TabLayout.Tab tab) {
                        super.onTabReselected(tab);
                    }
                }
        );
    

    that will do the job perfectly , and you can pad yourself in the back as i did myself :D

提交回复
热议问题