8
votes

I am new to android and stuck in a very basic problem.I am working on an application in which I need to swipe images on fling.On every image I have to add buttons dynamically.I am adding buttons using AddContentView() to add buttons.Everything is working fine but I want to set the position of buttons dynamically.I have read at many places,everyone is using addView() to add buttons and setting their positions.I have tried this

but it isn't working.Can anyone please tell me how to set the margins(position) of button using addContentView().Any help would highly be appreciated.

1

1 Answers

10
votes

Setting a buttons margin using addView works for me. Be sure to pass the right LayoutParams object to the ViewGroup that should hold your button.

FrameLayout fl = new FrameLayout(context);
Button b = new Button(context);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width, height);
params.setMargins(top, left, bottom, right);
fl.addView(b,params);

should work.