1
我正在創建一個文字遊戲,棋盤上的一堆方形瓷磚。我開始執行觸摸和移動瓷磚的動作事件並遇到問題。當我觸摸瓷磚(ACTION_DOWN)時,將其從當前視圖中移除並將其移動到另一個父視圖。我將其設置爲新佈局,但該佈局不受尊重,在新視圖中瓷磚將移至0,0。我有相同的代碼來定義ACTION_MOVE事件中的磁貼位置,並且在那裏按預期行事。所以我看到的是我觸摸瓷磚,它在新視圖中彈出到0,0,然後當我移動手指時,它會彈回到我的手指下方,並按我的預期移動。這裏是代碼:將RelativeLayout視圖添加到不尊重初始佈局
我的瓷磚類擴展視圖和我的板類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;
}