Search code examples
javaandroidhuawei-mobile-serviceshuawei-developersharmonyos

How to find the swipe direction of PageSlider while the user starts swiping the page in HarmonyOS?


I am writing a custom component in HarmonyOS using Java SDK and it is a custom page slider indicator. To do that I have added a PageChangedListener which provides three override methods.

public class CustomPageSliderIndicator extends Component implements PageSlider.PageChangedListener{

@Override
public void onPageSliding(int position, float positionOffset, int positionOffsetPixels) {}

@Override
public void onPageChosen(int i) {}

@Override
public void onPageSlideStateChanged(int i) { }
}

Whenever the user slides a page, onPageSliding will be called, here I am facing the problem that the position and positionOffset are the same for sliding right and left.

So, how to know the direction of sliding?


Solution

  • Introduce an instance variable (currentPosition) to keep track of the current page.

        private int currentPosition;
    
    ...
    
        pageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
                        @Override
                        public void onPageSliding(int itemPos, float itemPosOffset, int itemPosOffsetPixels) {
                        }
    
                        @Override
                        public void onPageSlideStateChanged(int state) {
                        }
    
                        @Override
                        public void onPageChosen(int position) {
                             if(currentPosition < position) {
                                // handle swipe LEFT
                            } else if(currentPosition > position){
                                // handle swipe RIGHT
                            }
                            currentPosition = position; // Update current position
                        }
                    });