How to change FloatingActionButton between Tabs?

后端 未结 7 741
囚心锁ツ
囚心锁ツ 2021-01-30 02:28

I\'m trying to implement FloatingActionButton from Google Design Support Library into two of three tabs, and according to t

7条回答
  •  盖世英雄少女心
    2021-01-30 03:06

    That's what worked for me:

    private boolean isFloatingActionButtonHidden = false;
    private int[] colorIntArray = {R.color.walking,R.color.running,R.color.biking,R.color.paddling,R.color.golfing};
    private int[] iconIntArray = {R.drawable.ic_walk_white,R.drawable.ic_run_white,R.drawable.ic_bike_white,R.drawable.ic_add_white,R.drawable.ic_arrow_back_white};
    
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }
    
        @Override
        public void onPageSelected(int position) {
        }
    
        @Override
        public void onPageScrollStateChanged(int state) {
            switch (state) {
                case ViewPager.SCROLL_STATE_SETTLING:
                    // This is triggered just before the view pager reaches the final state
                    // if you want to trigger the animation after the page reaches its final position
                    // just move this to "case ViewPager.SCROLL_STATE_IDLE:"
                    showFloatingActionButton(viewPager.getCurrentItem());
                    break;
                case ViewPager.SCROLL_STATE_IDLE:
                    // This is only triggered if user pulls to the left of the start or right of the end
                    if (isFloatingActionButtonHidden) {
                        showFloatingActionButton(viewPager.getCurrentItem());
                    }
                    break;
                default:
                    // in all other cases just hide the fab if it is not visable
                    if (!isFloatingActionButtonHidden) {
                        hideFloatingActionButton();
                    }
            }
       }
    });
    
    private void showFloatingActionButton(int position) {
        fab.setImageDrawable(getResources().getDrawable(iconIntArray[position], null));
    
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            floatingActionButton.setBackgroundTintList(getResources().getColorStateList(iconIntArray[position], getTheme()));
        } else {
            floatingActionButton.setBackgroundTintList(getResources().getColorStateList(iconIntArray[position]));
        }
    
        floatingActionButton.show();
    }
    
    private void hideFloatingActionButton() {
        isFloatingActionButtonHidden = true;
        floatingActionButton.hide();
    }
    

提交回复
热议问题