以编程方式重新排序RelativeLayout

时间:2011-02-16 12:58:04

标签: java android

我正在尝试创建一个单词混乱游戏,你可以在混乱的单词中向右或向左拖动一个字母,然后交换字母。以编程方式重新排序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中的循环依赖”的错误,但我不知道还有其他方法可以做到这一点。

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

是的,这个错误意味着你必须没有一个object1是toRightOf object2和object2 toLeftOf object 1

答案 1 :(得分:0)

我认为在你的情况下你不应该使用toRightOf和toLeftOf来定位你的视图,但是尝试只使用边距左边和边距顶部设置。通过这种方式,您的子视图将彼此独立,您可以通过更改其边距来移动它们。

答案 2 :(得分: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);
        }
    }
}