Drag an image only horizontally or vertically in a

2020-02-15 15:30发布

问题:

I want to control the dragging way of the image in android. It should be moved only in one direction. How can i control it?

回答1:

First, put a ScrollView inside a HorizontalScrollView, and the ImageView inside the innermost ScrollView.

Hierarchy will look like this:

  LinearLayout (ROOT)
  |
  +-- ScrollView (V)
       |
       +-- LinearLayout (1)
            |
            +-- HorizontalScrollView (H)
                |
                +-- LinearLayout (2)
                    |
                    +-- ImageView

And let me explain:

(V) scrolls in vertical direction only.

(H) scrolls in horizontal direction only.

(1) and (2) are linear layouts used immediately following any ScrollViews. Because, a ScrollView can host only one direct child.

Note on naming: There's only "ScrollView", and not "VerticalScrollView"

What happens when you drag the ImageView ?

Based on the very first direction of the gesture you make, if it's horizontal, the HorizontalScrollView will process the action, and the ScrollView will sit idle. And if the action was vertical, the ScrollView will process the action, and HorizontalScrollView will sit idle.