applibgroup / HarmonyOS-Knowledgebase

This repository contains code samples of HarmonyOS Training
Apache License 2.0
17 stars 6 forks source link

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

Closed Sanku-Yogesh closed 3 years ago

Sanku-Yogesh commented 3 years ago

Describe the query

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?

Create the query with harmonyos tag in stackoverflow and share the link here:

https://stackoverflow.com/questions/68540496/how-to-find-the-swipe-direction-of-pageslider-while-the-user-starts-swiping-the

Additional information

Developer Platform: Windows DevEco Studio version: 2.1.0.303 SDK API version: 5 SDK version: 2.1.1.21 Device: Not Required Device OS version: Not Required

Regards, Yogesh.

kanaksony commented 3 years ago

Answer replied on StackOverflow, please review the solution and confirm if it answers your query.

GowthamRayar commented 3 years ago

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
                    }
                });