2011-02-16 96 views
2

我正在嘗試創建一個單詞混雜遊戲,您將混亂的單詞和字母交換中的字母向右或向左拖動。以編程方式在RelativeLayout中重新排序項目的最佳方式是什麼?因此,當字母被拖動時,左側的字母被放置在被拖動的字母的右側。以編程方式重新排列RelativeLayout

我已經嘗試過這樣的基本測試。

public static void moveTile(Tile tile, int x, RelativeLayout parent) { 
    if (x < tile.getWidth()) { 
     RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
     params.addRule(RelativeLayout.LEFT_OF, tile.getId() - 1); 
     tile.setLayoutParams(params); 

     RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
     p.addRule(RelativeLayout.RIGHT_OF, tile.getId()); 
     Tile t = (Tile) parent.findViewById(tile.getId() - 1); 
     t.setLayoutParams(p); 
    } 
    parent.invalidate(); 
} 

但是,這會導致應用程序有關,我理解「循環依賴關係不能在RelativeLayout的存在」,但我只是不知道這樣做有什麼其他方法錯誤崩潰。

任何幫助將不勝感激。

回答

0

我結束了使用LinearLayout,只是之前或之後刪除瓷磚,並用當前選定的瓷磚替換它像這樣。

public static void moveTile(Tile tile, int x, LinearLayout parent) { 
    if (x < 0) { 

     int t = Math.abs(x)/tile.getWidth() + 1; 

     if (tile.getId() - t >= 0) { 
      Tile new_tile = (Tile) parent.findViewById(tile.getId() - t); 

      parent.removeViewAt(new_tile.getId()); 
      parent.addView(new_tile, tile.getId()); 

      int id = tile.getId(); 
      tile.setId(new_tile.getId()); 
      new_tile.setId(id); 
     } 
    } else if (x > tile.getWidth()) { 

     int t = x/tile.getWidth(); 

     if (tile.getId() + t < word.length()) { 
      Tile new_tile = (Tile) parent.findViewById(tile.getId() + t); 

      parent.removeViewAt(new_tile.getId()); 
      parent.addView(new_tile, tile.getId()); 

      int id = tile.getId(); 
      tile.setId(new_tile.getId()); 
      new_tile.setId(id); 
     } 
    } 
} 
2

是的,這個錯誤意味着你不能有一個object1是toRightOf對象2和對象2 toLeftOf對象1

+0

是的,我明白這一點。在我左右移動時如何完成字母定位的任何建議? – 2011-02-16 13:08:37

+1

在添加新工作之前刪除兩條規則,這樣就永遠不會有什麼時候什麼是循環的? – Dre 2011-02-16 13:33:25

0

我覺得你的情況,你不應該使用toRightOf和toLeftOf來定位你的意見,但嘗試使用剛剛保證金所有這些設置都是左邊界和餘下邊界。通過這種方式,您的子視圖將彼此獨立,您可以通過更改邊距來移動它們。

相關問題