Yesterday i tried to create a custom view where all the elements like buttons, imagebuttons, ... are placed around a circle with equal spacing.
My goal was to get this:
I tried this code:
public class CircleView extends RelativeLayout {
private OnDrop onDrop = null;
private int radius = -1;
private double step = -1;
private double angle = -1;
private static final int CENTER_ID = 111;
public CircleView(Context context, OnDrop onDrop, int radius, List<View> elements) {
super(context);
this.onDrop = onDrop;
this.radius = radius;
this.step = (2 * Math.PI) / elements.size();
RelativeLayout.LayoutParams layoutParamsView = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
this.setLayoutParams(layoutParamsView);
this.addView(this.createCenter(context));
for(View view : elements) {
this.addView(this.placeView(view));
}
}
private View placeView(View view) {
RelativeLayout.LayoutParams layoutParams = createNewRelativeLayoutParams();
int x = (int)(view.getWidth() / 2 + this.radius * Math.cos(this.angle));
int y = (int)(view.getHeight() / 2 + this.radius * Math.sin(this.angle));
this.angle += this.step;
layoutParams.setMargins(x, 0, 0, y);
view.setLayoutParams(layoutParams);
return view;
}
private View createCenter(Context context) {
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(Globals.DRAG_TARGET_SIZE, Globals.DRAG_TARGET_SIZE);
layoutParams.addRule(CENTER_HORIZONTAL);
layoutParams.addRule(CENTER_VERTICAL);
Button button = new Button(context);
button.setId(CENTER_ID);
button.setLayoutParams(layoutParams);
return button;
}
private RelativeLayout.LayoutParams createNewRelativeLayoutParams() {
RelativeLayout.LayoutParams layoutParameters = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParameters.addRule(RelativeLayout.ABOVE, CENTER_ID);
layoutParameters.addRule(RIGHT_OF, CENTER_ID);
return layoutParameters;
}
}
What i got from this code is this:
That means the creation of the circle with equal spacing between the elements is working quite good. But there is still a problem with the placing. Something is wrong with the x and y coordinate.
Can someone help me figuring out how to correct this offset?
I implemented my own Layout to place buttons circulary around a center point:
Use it like: