1

Hi i am very begginer for android and i have added Relative layout programatically on my blank Activity and so for everything is ok

Here my main requirement is i would like to set margins for that Relative-layout at four sides for this i have tried some code but that's not working please help me

my code:-

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

       // Creating a new RelativeLayout
        RelativeLayout ll = new RelativeLayout(this);
        ll.setBackgroundColor(getResources().getColor(R.color.red));

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);

        layoutParams.setMargins(10, 10, 10, 10);


        setContentView(ll);
}

2 Answers2

1

Just call setLayoutParams() after setting your margins:

        layoutParams.setMargins(10, 10, 10, 10);

        ll.setLayoutParams(layoutParams);// here
        setContentView(ll);

PS: In your case, it's better if you set your RelativeLayout from xml

Rami
  • 7,879
  • 12
  • 36
  • 66
-1

Just in case that you need it in XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="10dip">

</RelativeLayout>

Or you could set them by one

android:layout_marginBottom="10dip"
android:layout_marginTop="10dip"

And so on

Cipi
  • 1