8

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.

user1022105
  • 101
  • 1
  • 2
  • 5

1 Answers1

10

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.

js-
  • 1,632
  • 1
  • 14
  • 18
  • 1
    Thankyou very much for quick response.I am using addContentView() as I want to add button on top of images without taking any place from image's area.I have tried your solution but specifying params like this in addContentView() hasn't worked for me.I am using following code Button b = new Button(this); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(50,50); params.setMargins(100,300,30,10); addContentView(b,params); changing values in setMargins() makes no effect.Really sorry may be I am doing some basic mistake, please help me – user1022105 Nov 02 '11 at 16:17
  • Have you tried addView instead of addContentView, too? I have never used addContentView and can therefore not say whether can work. But i am just working on a project where i use setMargings with addView like in my example. It works very well for me. So either u try addView and it workds or maybe the mistake is somewhere else. – js- Nov 02 '11 at 16:48
  • I think you've forgotten " fl.setLayoutParams(params); " – johann Oct 20 '12 at 00:10