GridLayout(Android)中两个视图的交换位置

时间:2014-03-02 17:30:12

标签: android animation view grid-layout android-gridlayout

我编写了一个基本的游戏应用程序,它由可以通过滑动交换的块组成(类似于CandyCrush)。我成功识别了滑动手势但是我的代码改变了GridLayout中视图(块)的位置,只能在模拟器中工作,而不能在真实设备上工作(三星Galaxy S3)。

同样我找不到两种视图的动画交换方式。我已将android:animateLayoutChanges="true"添加到GridLayout XML,但它没有改变任何内容。

这是我的交换代码:

// 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();

这是App的截图:

enter image description here

1 个答案:

答案 0 :(得分:1)

您应该拥有布局的索引表,并在绘图方法中运行此索引以绘制每个块。 像那样:

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...

}

这个索引可以一直很有用,不仅仅是blit。