Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Button's margin programmatically

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.

like image 558
user1022105 Avatar asked Nov 02 '11 13:11

user1022105


People also ask

How do you set margin top programmatically?

Set LayoutParams to the view. To set margin to the view create LayoutParams instance, and set margin to the view. LinearLayout. LayoutParams layoutParams = new LinearLayout.

How do you set margin programmatically in constraint layout?

MarginLayoutParams layoutParams = new ConstraintLayout. MarginLayoutParams(newLayoutParams); layoutParams. setMargins(0, 0, 0, 0); toolbar. setLayoutParams(newLayoutParams);

How do I set margin programmatically in Cardview?

getLayoutParams(); layoutParams. setMargins(0, 0, SystemHelper. dpToPx(2), 0); myCardView. setLayoutParams(layoutParams);


1 Answers

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.

like image 165
js- Avatar answered Sep 22 '22 16:09

js-