In my activity there are two views. Both are in different parents. I have their coordinates with respect to the screen. How to interchange the location of the two views?
Asked
Active
Viewed 913 times
2 Answers
4
You will need to call the parent ViewGroup method removeView()
for both views then addView()
to add them back but swapper about.
So if your parent views are called mommy and daddy, one has a child called foo, the other a child called bar:
ViewGroup daddy = (ViewGroup)findViewById(R.id.daddy);
ViewGroup mommy = (ViewGroup)findViewById(R.id.mommy);
View foo = findViewById(R.id.foo);
View bar = findViewById(R.id.bar);
//detach children
daddy.removeView(foo);
mommy.removeView(bar);
//re-attach children
daddy.addView(bar);
mommy.addView(foo);
Read the reference for ViewGroup for more information about the removeView and addView methods and to see other available methods.

Moog
- 10,193
- 2
- 40
- 66
-
I do not know the id of the viewgroups. How to get the viewgroup of a view ? – John Watson Jul 12 '12 at 19:54
-
1You could just use the views getParent method on the child views – Moog Jul 12 '12 at 20:52
-
Each parent has more than two views, so exact interchange is not happening. – John Watson Jul 12 '12 at 22:58
-
1you can use the other version, `addView(View child, int index)` to specify the position at which to add the child into the parent – Moog Jul 13 '12 at 00:12
-
1to add to the previous comment if you need to find the original position of a child you can call `indexOfChild(View child)` on its parent. This is all on the documentation I linked to. – Moog Jul 13 '12 at 00:14
0
Try this:
int x1 = view1.getX();
int y1 = view1.getY();
view1.setX(view2.getX());
view1.setY(view2.getY());
view2.setX(x1);
view2.setY(y1);
You could also consider an animation effect to make this look nice.

CSmith
- 13,318
- 3
- 39
- 42
-
Merlin is correct, I missed the part about them belong to different parents – CSmith Jul 12 '12 at 19:18
-