简体   繁体   中英

Swipable Linear/Relative Layout (part 2)

I posted a question yesterday [ Swipable Linear/Relative Layout ]. The question did not get any answers. Meanwhile, I tried to solve my own problem. What I did is that I used the OnTouchListener to detect swipe and thus toggle the scientific part of the calculator (Read the question I posted earlier to get a clear idea) I used the following code :-

    RelativeLayout layout = (RelativeLayout)findViewById(R.id.advanced);
    layout.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    downX = event.getX();
                    return true;
                }
                case MotionEvent.ACTION_MOVE: {

                    upX = event.getX();
                    float deltaX = downX - upX;

                    swipe((int) deltaX);
                    return true;
                }
                case MotionEvent.ACTION_UP: {
                    downX = 0;
                }
            }
            return true;
        }

and the swipe method is :-

private void swipe(int distance) {
    RelativeLayout layout = (RelativeLayout)findViewById(R.id.advanced);
    LinearLayout.LayoutParams head_params = (LinearLayout.LayoutParams)layout.getLayoutParams();
    head_params.setMargins(-distance, 0, 0, 0); //substitute parameters for left, top, right, bottom
    layout.setLayoutParams(head_params);
}

The code works fine and achieves what it was meant to be till a certain extent. The problem is that, the swipe is buggy,ie, it kind of flashes when I swipe it and also, it is very slow. Please tell me how to implement this correctly. Shall I use ViewPager or something else. Please enlighten me. Thanks

The reason this is buggy is because you've registered a touch listener on the view you're moving as well. This causes the touch listener to return 'twitchy' values. One approach you could take is putting the listener on a parent view that is stationary, and using that to update the child view. I would also recommend looking into using a GestureDetector instead, it does most of the touch logic for you and provides some very useful methods through a listener.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM