Setting Margin for widgets Programmatically

In this tutorial, I am going to explain how we can set margin for widgets programmatically. Using XML, its through layout_marginLeft, layout_marginRight, layout_marginTop and layout_marginBottom.

Actually, I spent a quite some time in this. I tried with this class "android.view.ViewGroup.LayoutParams". But after trying for quite sometime, I realized the actual class, for that is "android.widget.LinearLayout.LayoutParams". We can use any layout, not only LinearLayout. But, it should be from widget package.

The function is setMargins(left, top, right, bottom); the four arguments shows the margin for four sides respectively.


TextView tv = new TextView(this);
LayoutParams params = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
params.setMargins(100, 20, 0, 0);
layout.addView(tv, params);


The screenshot of the result is,

Comments

Popular posts from this blog

AlarmManager and Notification in Android

Swipe Action and ViewFlipper in Android

Open Gallery and get the selected image in appplication