I was working on a game on Android studio where user touch drives tiles to combine. To do this, I have used a GridLayout separated into rows and columns. The value is displayed with imageview and all gridlayout cells are linked to a separate cell class which includes imageview ID's. I implemented a listener on each image view to detect when a swiping motion occured. The code for initalizing the board and listeners is below:
for(int i = 0; i<noOfBlocks; i++) {
for (int j = 0; j < noOfBlocks; j++) {
ImageView imageView = new ImageView(this);
imageView.setId(iDcnt);
imageView.setLayoutParams(new ViewGroup.LayoutParams(widthOfBlock, widthOfBlock));
imageView.setMaxHeight(widthOfBlock);
imageView.setMaxWidth(widthOfBlock);
int randomNum = (int) Math.floor(random.nextDouble() * gamepiece.length);
imageView.setImageResource(gamepiece[randomNum]);
Cell c = new Cell(i + 1, j+1, randomNum, imageView.getId());
imageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
SquarePlay s = null;
try {
s = new SquarePlay();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
s.onSwipeEvent(event);
return false;
}
});
gameBoard.addView(imageView);
iDcnt++;
}
The OnTouch events are handled in a separate class in the method which is shown below:
float x1, x2, y1, y2, dx, dy;
public void onSwipeEvent(MotionEvent event){
switch(event.getAction()) {
case(MotionEvent.ACTION_DOWN):
x1 = event.getX();
y1 = event.getY();
break;
case(MotionEvent.ACTION_UP): {
x2 = event.getX();
y2 = event.getY();
dx = x2-x1;
dy = y2-y1;
if(Math.abs(dx) > Math.abs(dy)) {
if(dx>0)
onSwipeRight();
else
onSwipeLeft();
} else {
if(dy>0)
onSwipeDown();
else
onSwipeUp();
}
}
}
}
private void onSwipeLeft() {
System.exit(0);
}
private void onSwipeRight() {
System.exit(0);
}
private void onSwipeUp() {
System.exit(0);
}
private void onSwipeDown() {
System.exit(0);
}
NOTE:System.exit is just there to test if this works.
The App loads but does not produce a response from the swipe events, Does anyone have any suggestions on how to resolve this issue?
Thank you :)