Reputation: 331
I'm trying to create a word jumble game where you drag a letter right or left in the jumbled word and the letters swap. What is the best way to reorder items in a RelativeLayout programmatically so when the letter is dragged left the letters that the tile passes are positioned to the right of the dragged letter.
I've tried something like this as a basic test.
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();
}
But this causes the app to crash with an error about "Circular dependancies cannot exist in a RelativeLayout" which I understand but I'm just not sure what other way to do this.
Any help will be much appreciated.
Upvotes: 2
Views: 1880
Reputation: 331
I ended up using a LinearLayout and just removing the tile before or after and replacing it with the currently selected tile something like this.
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);
}
}
}
Upvotes: 0
Reputation: 21639
I think in your case you should not use toRightOf and toLeftOf to position your views but try to use just margin left and margin top setting for all of them. In this way your child views would be independed of each other and you can move them around by changing their margins.
Upvotes: 0
Reputation: 1778
Yes, this error means that you must not have an object1 be toRightOf object2 and object2 toLeftOf object 1
Upvotes: 2