How to do a drag slide view in Android

后端 未结 1 1889
伪装坚强ぢ
伪装坚强ぢ 2021-01-07 03:24

I need to be able to drag-slide a listview to the left and out of view while exposing another listview that is underneath the first listview. How can I go about doing this?

1条回答
  •  渐次进展
    2021-01-07 04:22

    You can use a OnTouchListener and resize or move some view on ACTION_MOVE. Remember to call setClickable(true) to make sure ACTION_MOVE gets called.

    There goes an example with the sliding view at the bottom:

    Layout:

    
    
        
    
            (more content)
    
        
        
    
            
    
            (more content)
    
        
    
    
    

    Setting up the views:

    View slidingView = ...
    View draggableView = ... //placed inside slidingView, this is where you touch and drag
    draggableView.setOnTouchListener(new TouchListener(slidingView));
    draggableView.setClickable(true); //if not set, only ACTION_DOWN gets called, ACTION_MOVE doesn't
    

    Listener:

    private class TouchListener implements View.OnTouchListener{
    
            View slidingView;
    
            int initHeight;
            float initPos;
            ViewGroup.LayoutParams params;
    
            private TouchListener(View slidingView) {
                this.slidingView = slidingView;
            }
    
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(params == null){
                    params = slidingView.getLayoutParams();
                }
    
                switch (event.getActionMasked()){
                    case ACTION_DOWN: //get initial state
                        initHeight = slidingView.getHeight();
                        initPos = event.getRawY();
                        break;
                    case ACTION_MOVE: //do the sliding
                        float dPos = initPos - event.getRawY();
                        params.height = Math.round(initHeight + dPos);
                        slidingView.requestLayout(); //refresh layout
                        break;
                }
    
                return false;
            }
        }
    

    Note: If ACTION_MOVE still doesn't get called, try calling setFocusable in addition to setClickable. I didn't need to do this when my "draggable view" was a TextView though.

    0 讨论(0)
提交回复
热议问题