将视图添加到RelativeLayout不尊重初始布局

时间:2014-02-19 22:51:27

标签: android android-layout

我正在创建一个文字游戏,一块方形瓷砖在板上。我开始实施触摸和移动瓷砖并出现问题的动作事件。当我触摸一个图块(ACTION_DOWN)时,我将其从当前视图中移除并将其移动到另一个父视图。我设置了它的新布局但是没有遵循该布局,图块在新视图中移动到0,0。我有相同的代码用于在ACTION_MOVE事件中定义磁贴位置,并且它按预期运行。所以我看到的是我触摸一个瓷砖,它在新视图中弹出到0,0然后当我移动我的手指时它会弹回我的手指并按照我的预期移动。这是代码:

My Tile类扩展了View,我的棋盘类TileViewContainer扩展了RelativeLayout。

当我创建一个磁贴时,我将其注册为触摸事件,如下所示:

TileViewContainer gameBoard = (TileViewContainer) findViewById(R.id.gameBoard);
tile.setOnTouchListener(gameBoard);

这是我的OnTouchListener:

    @Override
public boolean onTouch(View v, MotionEvent event) {

    final int X = (int) event.getRawX();
    final int Y = (int) event.getRawY();

    if(tileBoard == null)
        tileBoard = (TileBoard) findViewById(R.id.tileBoard);
    if(tileTray == null)
        tileTray = (TileTray) findViewById(R.id.tileTray);

    Tile tile = (Tile) v;
    TileView parent = tile.lastParent;
    Rect rect = null;
    int size = tileBoard.mTileSize;

    switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:   

            //Add tile to container
            tile.removeParent();
            this.addView(tile);
            rect = new Rect(X-(size/2), Y-(size), X-(size/2)+size, Y-(size)+size);
            tile.layout(rect.left, rect.top, rect.right, rect.bottom);  
            break;

        case MotionEvent.ACTION_UP:
            print("action up");
            break;
        case MotionEvent.ACTION_POINTER_DOWN:
            print("pointer down");
            break;
        case MotionEvent.ACTION_POINTER_UP:
            print("pointer up");
            break;
        case MotionEvent.ACTION_MOVE:

            //Move tile
            rect = new Rect(X-(size/2) , Y-(size)  , X-(size/2)+size, Y-(size)+size);
            tile.layout(rect.left, rect.top, rect.right, rect.bottom);
            break;
    }

    this.invalidate();
    return true;   

}

1 个答案:

答案 0 :(得分:1)

我找到了解决其他任何人的解决方案。我改变了ACTION_DOWN案例:

//Add tile to container
tile.removeParent();
this.addView(tile);
rect = new Rect(X-(size/2), Y-(size), X-(size/2)+size, Y-(size)+size);   
tile.layout(rect.left, rect.top, rect.right, rect.bottom); 
break;

对此:

//Add tile to container
tile.removeParent();
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(sizeScaled, sizeScaled);
params.leftMargin = X-sizeScaled/2;
params.topMargin = Y-sizeScaled;
addView(tile, params);
break;

似乎我需要为初始放置创建一个新的LayoutParams。在移动部分设置tile.layout仍然可以正常工作。