Left-right arrow indicators over a ViewPager

前端 未结 5 1425
小蘑菇
小蘑菇 2021-01-30 15:04

I want to show left and right arrows over my ViewPager, to indicate swiping.

I added two ImageButtons over the ViewPager-element but those areas then block the ViewPager

5条回答
  •  余生分开走
    2021-01-30 15:13

    Implement left & right arrow buttons in your fragment. Then register their onClick in your activity and call viewpager's arrowScroll method to scroll the viewPager programmatically.

    public void onRightClick(View view) {
        viewPager.arrowScroll(ViewPager.FOCUS_RIGHT);
    }
    
    public void onLeftClick(View view) {
        viewPager.arrowScroll(ViewPager.FOCUS_LEFT);
    }
    

    Create a method to toggle left/right arrow visibility in your fragment.

    public void toggleArrowVisibility(boolean isAtZeroIndex, boolean isAtLastIndex) {
        if(isAtZeroIndex)
            leftBtn.setVisibility(View.INVISIBLE);
        else
            leftBtn.setVisibility(View.VISIBLE);
        if(isAtLastIndex)
            rightBtn.setVisibility(View.INVISIBLE);
        else
            rightBtn.setVisibility(View.VISIBLE);
    
    }
    

    Now implement ViewPager.OnPageChangeListener in your activity. Use SmartFragmentStatePagerAdapter to keep track of registered fragments in memory.

    @Override
    public void onPageSelected(int position) {
        MyFragment fragment = (MyFragment) smartAdapter.getRegisteredFragment(position);
        fragment.toggleArrowVisibility(position == 0, position == list.size() - 1);
    }
    

提交回复
热议问题