2016-08-24 49 views
0

我是初學者,但我想創建一個遊戲。現在我正在爲我的英雄做移動功能。當我觸摸圖像並將其移動到右側時,英雄將從原始位置以每秒100dp的速度移動到右側,但它無法工作。無法更新onTouch事件中的新位置

下面是我用我的移動功能的代碼:

public View.OnTouchListener move = new View.OnTouchListener() { 
    private float x, y; 
    private int mx, my, hx, hy; 

    public boolean onTouch(final View v, MotionEvent event) { 
     if ((event.getAction() == MotionEvent.ACTION_DOWN)) { 

      x = event.getX(); 
      y = event.getY(); 
      mx = (int) (event.getRawX() - x); 
      my = (int) (event.getRawY() - y); 

     } else if ((event.getAction() == MotionEvent.ACTION_MOVE)) { 

      hx = (int) (event.getRawX() - x); 
      hy = (int) (event.getRawY() - y); 
      v.layout(hx, hy, hx + v.getWidth(), hy + v.getHeight()); 

     } else if ((event.getAction() == MotionEvent.ACTION_UP)) { 

      while (hx > mx) { 
       final Handler handler = new Handler(); 
       handler.postDelayed(new Runnable() { 
        @Override 
        public void run() { 
         mx += 100; 
         v.layout(mx, my, mx + v.getWidth(), my + v.getHeight()); 
        } 
       }, 1000); 
      } 
     } 
     Log.e("x =", String.valueOf(x) + " y =" + String.valueOf(y)); 
     Log.e("hx =", String.valueOf(hx) + " hy =" + String.valueOf(hy)); 
     Log.e("mx =", String.valueOf(mx) + " my =" + String.valueOf(my)); 
     return true; 
    } 
}; 

回答

0

ACTION_MOVEACTION_UP做到這一點:

RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams(); 

//edit layout params according to your need 
view.setLayoutParams(layoutParams); 
+0

在ACTION_MOVE和ACTION_UP – Ashish

+0

做到這一點,請添加一些解釋你的答案。在SO上不鼓勵使用僅有代碼的答案。謝謝。 –

+0

謝謝你,它現在得到移動:) –