2017-08-22 80 views
0

我目前正在開發一個應用程序,允許用戶在線性佈局內添加相對佈局,線性佈局或嵌套線性佈局,這是一個滾動視圖的子視圖。當添加相對佈局或線性佈局時,滾動似乎可以正常工作,但是,一旦添加了嵌套線性佈局,滾動就成了問題。基本上,我希望滾動視圖開始滾動,一旦我的拖動視圖進入x屏幕頂部/底部的範圍內。有什麼建議?下面是我的一些代碼,以幫助在線性佈局中拖放滾動

protected class myDragEventListener implements View.OnDragListener { 
    // This is the method that the system calls when it dispatches a drag event to the listener. 
    public boolean onDrag(View v, DragEvent event) { 
     // Defines a variable to store the action type for the incoming event 
     final int action = event.getAction(); 
     Point touchPosition = getTouchPositionFromDragEvent(v, event); 
     Log.d("y", String.format("%s", String.format("%s", eventTouchYCoord))); 
     //View dragView = (View) event.getLocalState(); 
     // Handles each of the expected events 
     switch(action) { 
      case DragEvent.ACTION_DRAG_STARTED: 
       return true; 
      case DragEvent.ACTION_DRAG_ENTERED: 
       return true; 
      case DragEvent.ACTION_DRAG_LOCATION: 
       Log.d("point", touchPosition.toString()); 
       if (touchPosition.y > (absoluteBottom + mScrollDistance - 350)){ 
        Log.d("bottom", "greater"); 
        Log.d("actionbar", String.format("%s", actionBarHeight())); 
        homeScroll.scrollBy(0, 30); 
       } 
       if (touchPosition.y < (actionBarHeight + 350)){ 
        Log.d("top", "greater"); 
        homeScroll.scrollBy(0, -30); 
       } 
       break; 

getTouchPositionFromDragEvent方法

public static Point getTouchPositionFromDragEvent(View item, DragEvent event) { 
    Rect rItem = new Rect(); 
    item.getGlobalVisibleRect(rItem); 
    return new Point(rItem.left + Math.round(event.getX()), rItem.top + Math.round(event.getY())); 
} 

onScrollChangedListener方法

homeScroll.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { 
     @Override 
     public void onScrollChanged() { 
      mScrollDistance = homeScroll.getScrollY(); 
      int[] coords = new int[2]; 
      homeScroll.getLocationOnScreen(coords); 
      absoluteTop = coords[1]; 
      absoluteBottom = coords[1] + homeScroll.getHeight(); 
     } 
    }); 
+0

我想一個更好的問題可能是,我如何才能拖動視圖的絕對位置,這意味着,無論我多麼滾動,y位置將是absoluteTop之間的某處和absoluteBottom。截至目前,getTouchPositionFromDragEvent返回整個佈局的x,y座標,並考慮滾動。 –

回答

0

它總是最好的實踐來實現在XML文件中滾動屬性。這是你想要滾動它的一面。或者在Palette中,你會發現垂直和水平滾動的scrollview選項。只需拖放到你想要放置的地方。

<ScrollView 
 
    xmlns:android="http://schemas.android.com/apk/res/android" 
 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
 
    android:layout_width="match_parent" 
 
    android:layout_height="match_parent"> 
 
    
 
    </ScrollView>

+0

我已經在我的xml中實現了scrollview。我可以滾動我的容器就好了。我的問題是當我拖動視圖並嘗試滾動時。 –