I am new to android. I want to move the image from left to right and from right to left. When the user touches the right image of the image, he will move to the right. The same thing happens when the user touches the right side of the image. But the image will move the predefined point along the x axis.
For example: the image will move p1 (100,100), p2 (150,100), p3 (200,100), p4 (250 100) through these points sequentially. If the user touches the left side of p1, he will remain at the current position. The same thing will happen on p4. I can move the image from p1 to p2 and p2 to p1. when i add p3 and p4 it doesn't work as i expected.
Here is my GameView class.
public class GameView extends SurfaceView{
private Bitmap BG_image;
private SurfaceHolder holder;
int x;
int y;
private int srcX=100;
private int srcY=100;
int replaceX=0,areaThreshold=50;
int distance=50;
public GameView(Context context) {
super(context);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Canvas c = holder.lockCanvas(null);
onDraw(c);
holder.unlockCanvasAndPost(c);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
BG_image = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
Bitmap.createScaledBitmap(BG_image, BG_image.getWidth(), BG_image.getHeight(), false);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
updateX(srcX);
replaceX=(int)ev.getX();
int StartX=0, EndX=0;
StartX=replaceX-areaThreshold;
EndX=replaceX+areaThreshold;
if(StartX<=100){
SurfaceHolder holder=getHolder();
Canvas myCanvas=holder.lockCanvas(null);
onDraw(myCanvas);
holder.unlockCanvasAndPost(myCanvas);
srcX=100;
}
else if(StartX>100 && StartX<250){
SurfaceHolder holder=getHolder();
Canvas myCanvas=holder.lockCanvas(null);
onDraw(myCanvas);
holder.unlockCanvasAndPost(myCanvas);
srcX=srcX+distance;
}
if(EndX>100 && EndX<250){
SurfaceHolder holder=getHolder();
Canvas myCanvas=holder.lockCanvas(null);
onDraw(myCanvas);
holder.unlockCanvasAndPost(myCanvas);
srcX=srcX-distance;
}
else if(EndX>250){
SurfaceHolder holder=getHolder();
Canvas myCanvas=holder.lockCanvas(null);
onDraw(myCanvas);
holder.unlockCanvasAndPost(myCanvas);
srcX=250;
}
return super.onTouchEvent(ev);
}
@Override
protected void onDraw(Canvas canvas) {
updateX(srcX);
Paint paint = new Paint();
canvas.drawColor(Color.BLACK);
canvas.drawRect(new Rect(0,0,getWidth(),getHeight()),paint);
canvas.drawBitmap(BG_image, srcX, srcY, null);
}
private int updateX(int srcX){
this.srcX =srcX;
return srcX ;
}
}
.
, !