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.
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.
MarginLayoutParams layoutParams = new ConstraintLayout. MarginLayoutParams(newLayoutParams); layoutParams. setMargins(0, 0, 0, 0); toolbar. setLayoutParams(newLayoutParams);
getLayoutParams(); layoutParams. setMargins(0, 0, SystemHelper. dpToPx(2), 0); myCardView. setLayoutParams(layoutParams);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With