2012-03-10 59 views
1

我已經用image實現了一個應用程序。在我的應用程序中,當用戶觸摸圖像時,我使用圖像,我想用手指觸摸移動圖像。我已經實現我的應用程序如下:如何在用戶觸摸事件時在xml佈局上移動圖像?

((ImageView)findViewById(R.id.imageView1)).setOnTouchListener(new OnTouchListener() { 
    @Override 
    public boolean onTouch(View v, MotionEvent event) { 
     switch (event.getAction()) { 
     case MotionEvent.ACTION_MOVE: 
      //I would like to Move image along with user finger touch code 
      break; 

     default: 
      break; 
     } 
     return false; 
    } 
}); 

從上面的代碼我不能移動圖像與用戶手指一起。

回答

1

只是一個建議,它爲我工作:

製作返回false,onTouch真()方法

0

我'm使用此代碼實現此目的

package mani.droid.touchdrag; 

import android.os.Bundle; 
import android.app.Activity; 
import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.graphics.Canvas; 
import android.util.Log; 
import android.view.MotionEvent; 
import android.view.View; 

public class MainActivity extends Activity { 

Bitmap img; 
float x; 
float y; 
boolean isStarted = false; 

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

    img = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); 

    setContentView(new MyScreen(this)); 
} 

public class MyScreen extends View { 

    Context context; 

    public MyScreen(Context context) { 
     super(context); 
     // TODO Auto-generated constructor stub 
     this.context = context; 
    } 

    @Override 
    public boolean onTouchEvent(MotionEvent event) { 
     // TODO Auto-generated method stub 
     switch(event.getAction()) 
     { 
      case MotionEvent.ACTION_DOWN: 
       float xdiff = Math.abs(x - event.getX()); 
       float ydiff = Math.abs(y - event.getY()); 
       if(xdiff < 23 || ydiff < 23){ 
        isStarted = true; 
       } 
       break; 

      case MotionEvent.ACTION_MOVE: 
       if(isStarted) 
       { 
        x = event.getX() - img.getWidth()/2; 
        y = event.getY() - img.getHeight()/2; 
        Log.v("X:" + x, "Y: " + y); 
        this.invalidate(); 
       } 
       break; 

      case MotionEvent.ACTION_UP: 
       isStarted = false; 

     } 
     return true; 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     // TODO Auto-generated method stub 
     super.onDraw(canvas); 

     canvas.drawBitmap(img, x, y, null); 
    } 
} 
} 

和它的工作完美...