Question

I have programmed a basic gaming App that consists of blocks which can be exchanged by a swipe (similar to CandyCrush). I succeeded in recognizing the swipe gesture but my code that changes the positions of the Views (blocks) within a GridLayout does only work in the emulator but not on a real device (Samsung Galaxy S3).

Also I couldn't find a way of animating the interchange of the two views. I've added android:animateLayoutChanges="true" to the GridLayout XML but it didn't change anything.

Here's my exchanging code:

// change to blocks positions in grid layout
GridLayout.LayoutParams sourceParams = (GridLayout.LayoutParams)this.imageView.getLayoutParams();
GridLayout.LayoutParams targetParams = (GridLayout.LayoutParams)otherBlock.imageView.getLayoutParams();

GridLayout.Spec sourceRowSpec = sourceParams.rowSpec;
GridLayout.Spec sourceColumnSpec = sourceParams.columnSpec;
sourceParams.rowSpec = targetParams.rowSpec;
sourceParams.columnSpec = targetParams.columnSpec;
targetParams.rowSpec = sourceRowSpec;
targetParams.columnSpec = sourceColumnSpec;

this.imageView.setLayoutParams(sourceParams);
otherBlock.imageView.setLayoutParams(targetParams);

gameGridLayout.requestLayout();

And here's a screenshot of the App:

enter image description here

Was it helpful?

Solution

You should have an index table of your layout, and in your drawing method you run through this index to draw each block. Like that:

private int [][] index;

void onDraw(Canvas canvas)  {
    for (int i = 0; i < MAX_BLOCK_HEIGHT; i++)  {
        for (int j = 0; j < MAX_BLOCK_WIDTH; j++)   {
            // Draw block index[i][j]
        }
    }
}

void swapBlock(int blockX, int blockY, int relativePos) {
    int tmpBlock = index[blockY][blockX];
    if (relativePos == AT_LEFT) {
        index[blockY][blockX] = index[blockY][blockX - 1];
        index[blockY][blockX - 1] = tmpBlock;
    }
    // And so on...

}

And this index can be helpful all the time, not only for blit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top