2012-11-24 45 views
2

我正在使用拖動遊戲,但我遇到了一個小問題,那就是當我在視圖中單擊時,影子生成器首先出現在右上角,然後隨觸摸位置移動。安卓中的暗影生成器

此外,陰影構建器比初始視圖小。我怎樣才能把它作爲初始視圖?

private final class MyTouchListener implements OnTouchListener { 
    public boolean onTouch(View view, MotionEvent motionEvent) { 

     if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) { 
      ClipData data = ClipData.newPlainText("", ""); 
      DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view); 
      view.startDrag(data, shadowBuilder, view, 0); 
      view.setVisibility(View.INVISIBLE); 
      return true; 
     } else { 
      return false; 
     } 
    } 
} 

回答

5

我可能會遲到,但...... 你必須計算出觸摸點和您可拖動左上角之間的偏移,並具有自定義DragShadowBuilder使用它。

下面是偏移量代碼:

@Override 
public boolean onTouch(View view, MotionEvent event) { 

    switch(event.getAction()) { 

     case MotionEvent.ACTION_DOWN : { 

      Point offset = new Point((int) event.getX(), (int) event.getY()); 

      ClipData data = ClipData.newPlainText("", ""); 
      DragShadowBuilder shadowBuilder = new CustomDragShadowBuilder(container, offset); 
      view.startDrag(data, shadowBuilder, container, 0); 
      view.setVisibility(View.INVISIBLE); 
     } 
    } 

    return true; 
} 

這裏是自定義生成器的代碼:

import android.graphics.Point; 
import android.view.View; 

public class CustomDragShadowBuilder extends View.DragShadowBuilder { 

// ------------------------------------------------------------------------------------------ 
// Private attributes : 
private Point _offset; 
// ------------------------------------------------------------------------------------------ 



// ------------------------------------------------------------------------------------------ 
// Constructor : 
public CustomDragShadowBuilder(View view, Point offset) { 

    // Stores the View parameter passed to myDragShadowBuilder. 
    super(view); 

    // Save the offset : 
    _offset = offset; 
} 
// ------------------------------------------------------------------------------------------ 



// ------------------------------------------------------------------------------------------ 
// Defines a callback that sends the drag shadow dimensions and touch point back to the system. 
@Override 
public void onProvideShadowMetrics (Point size, Point touch) { 

    // Set the shadow size : 
    size.set(getView().getWidth(), getView().getHeight()); 

    // Sets the touch point's position to be in the middle of the drag shadow 
    touch.set(_offset.x, _offset.y); 
} 
// ------------------------------------------------------------------------------------------ 
} 
+0

謝謝你,只是請立即修正錯誤,你寫的容器而不是查看第一碼。 – Michal

+0

對不起,它是固定的! –