2015-06-18 1 views
0

Я создал onTouchEvent, чтобы найти, где пользователь прикасается и перемещает мой объект в эту позицию. то, что я хотел бы сделать, это если пользователь нажимает на экран, объект перемещается на определенное расстояние прямо вверх. и то же самое для других направлений. Я знаю, что мне нужно несколько инструкций, чтобы сделать это, но я не знаю, как это сделать. Кто-нибудь есть какие-либо советы или знают, как это сделать, благодаряAndroid: Как определить, нажимает ли пользователь вверх, вниз, влево или вправо?

public boolean onTouchEvent(MotionEvent ev) { 

    if(ev.getAction() == MotionEvent.ACTION_DOWN) { 
     // the new image position became where you touched 
     x = ev.getX(); 
     y = ev.getY(); 


    // if statement to detect where user presses down   
    if(){ 
    } 
     // redraw the image at the new position 
     Draw.this.invalidate(); 
    } 
    return true; 
} 

ответ

0

Попробуйте

public boolean onTouchEvent(MotionEvent ev) { 

    initialise boolean actionDownFlag = false; 

    if(ev.getAction() == MotionEvent.ACTION_DOWN) { 
     // the new image position became where you touched 
     x = (int) ev.getX(); 
     y = (int) ev.getY(); 


    // if statement to detect where user presses down   
    if(actionDownFlag){ 

     catcher.moveDown(); 
    } 
     // redraw the image at the new position 
     Draw.this.invalidate(); 
    } 
    return true; 
} 

    public void moveDown(){ 

     posX -= //WhereEver you want to move the position (-5); 
    } 
0

попробовать это:

layout_counter.setOnTouchListener(new OnTouchListener() { 
    @Override 
    public boolean onTouch(View view, MotionEvent event) 
    { 
     if (currentState != State.EDIT_MOVE) return false; 

     FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) view.getLayoutParams(); 
     if (view.getId() != R.id.layout_counter) return false; 

     switch (event.getAction()) 
     { 
      case MotionEvent.ACTION_MOVE: 
       params.topMargin = (int) event.getRawY() - view.getHeight(); 
       params.leftMargin = (int) event.getRawX() - (view.getWidth()/2); 
       view.setLayoutParams(params); 
       break; 

      case MotionEvent.ACTION_UP: 
       params.topMargin = (int) event.getRawY() - view.getHeight(); 
       params.leftMargin = (int) event.getRawX() - (view.getWidth()/2); 
       view.setLayoutParams(params); 
       break; 

      case MotionEvent.ACTION_DOWN: 
       view.setLayoutParams(params); 
       break; 
     } 

     return true; 
    } 
}); 
0

Вы должны использовать OnLongClickListener, который лучше подходит с сопротивлением и кадр андроида:

Обратите внимание на следующий пример:

public class MainActivity extends Activity { 

    private ImageView myImage; 
    private static final String IMAGEVIEW_TAG = "The Android Logo"; 

/** Called when the activity is first created. */ 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.activity_main); 
     myImage = (ImageView)findViewById(R.id.image); 
     // Sets the tag 
     myImage.setTag(IMAGEVIEW_TAG); 

     // set the listener to the dragging data 
     myImage.setOnLongClickListener(new MyClickListener()); 

     findViewById(R.id.toplinear).setOnDragListener(new MyDragListener()); 
     findViewById(R.id.bottomlinear).setOnDragListener(new MyDragListener()); 

    } 

    private final class MyClickListener implements OnLongClickListener { 

     // called when the item is long-clicked 
     @Override 
     public boolean onLongClick(View view) { 
     // TODO Auto-generated method stub 

      // create it from the object's tag 
      ClipData.Item item = new ClipData.Item((CharSequence)view.getTag()); 

      String[] mimeTypes = { ClipDescription.MIMETYPE_TEXT_PLAIN }; 
      ClipData data = new ClipData(view.getTag().toString(), mimeTypes, item); 
      DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view); 

      view.startDrag(data, //data to be dragged 
          shadowBuilder, //drag shadow 
          view, //local data about the drag and drop operation 
          0 //no needed flags 
         ); 


      view.setVisibility(View.INVISIBLE); 
      return true; 
     } 
    } 

    class MyDragListener implements OnDragListener { 
     Drawable normalShape = getResources().getDrawable(R.drawable.normal_shape); 
     Drawable targetShape = getResources().getDrawable(R.drawable.target_shape); 

     @Override 
     public boolean onDrag(View v, DragEvent event) { 

      // Handles each of the expected events 
      switch (event.getAction()) { 

      //signal for the start of a drag and drop operation. 
      case DragEvent.ACTION_DRAG_STARTED: 
       // do nothing 
       break; 

      //the drag point has entered the bounding box of the View 
      case DragEvent.ACTION_DRAG_ENTERED: 
       v.setBackground(targetShape); //change the shape of the view 
       break; 

      //the user has moved the drag shadow outside the bounding box of the View 
      case DragEvent.ACTION_DRAG_EXITED: 
       v.setBackground(normalShape); //change the shape of the view back to normal 
       break; 

      //drag shadow has been released,the drag point is within the bounding box of the View 
      case DragEvent.ACTION_DROP: 
       // if the view is the bottomlinear, we accept the drag item 
        if(v == findViewById(R.id.bottomlinear)) { 
         View view = (View) event.getLocalState(); 
         ViewGroup viewgroup = (ViewGroup) view.getParent(); 
         viewgroup.removeView(view); 

         //change the text 
         TextView text = (TextView) v.findViewById(R.id.text); 
         text.setText("The item is dropped"); 

         LinearLayout containView = (LinearLayout) v; 
         containView.addView(view); 
         view.setVisibility(View.VISIBLE); 
        } else { 
         View view = (View) event.getLocalState(); 
         view.setVisibility(View.VISIBLE); 
         Context context = getApplicationContext(); 
         Toast.makeText(context, "You can't drop the image here", 
               Toast.LENGTH_LONG).show(); 
         break; 
        } 
        break; 

      //the drag and drop operation has concluded. 
      case DragEvent.ACTION_DRAG_ENDED: 
       v.setBackground(normalShape); //go back to normal shape 

      default: 
       break; 
      } 
      return true; 
     } 
    } 
} 

Приведенный выше код взят из here демонстрирует, как перетащить и как сделать что-то при перетаскивании .. я использовал что-то подобное, как хорошо.

Смежные вопросы