nilkash
nilkash

Reputation: 7536

create and set margin programmatic for relative layout android

Hi I am developing android application in which I am creating relative layout programmatic and tried to set margin for that and Added it into linear layout which have orientation linear. So here is my code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/screen_background"
    tools:context=".ChooseChannelsFragment" >

    <LinearLayout 
      android:id="@+id/main_outer_llt"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:orientation="horizontal"
      >

  </LinearLayout> 

</RelativeLayout>

and inside fragment I am adding relative layout like this

RelativeLayout relativeLayout = new RelativeLayout(getActivity());
    RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(200, 80);
    relativeParams.setMargins(20, 20, 20, 20);
    relativeLayout.setLayoutParams(relativeParams);
    relativeLayout.setBackgroundColor(getResources().getColor(R.color.green_color));
    linearLayout.addView(relativeLayout);

It create layout with given color and size but not accepting margins. Am I doing something wrong? How to do this? Need Help. Thank you.

Upvotes: 1

Views: 10010

Answers (3)

milosmns
milosmns

Reputation: 3793

As others suggested, layout_margin# is the space between the parent's # edge and your view.

  • # replaces "Left", "Right", "Top" or "Bottom"

Getting/setting margins worked for me with:

ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mView.getLayoutParams();
params.topMargin += 20;
mView.requestLayout(); // important

Of course, my View was indeed a ViewGroup and the parent was a ViewGroup as well. In most cases, you should cast your layout params to the parent's View class LayoutParams (in this case it's ViewGroup and RelativeLayout)

Upvotes: 2

Victor Elias
Victor Elias

Reputation: 710

The LayoutParams type you use on a view should actually be from its parent.

So, if you're adding a RelativeLayout to a LinearLayout, the LayoutParams you set to your RelativeLayout should actually be a LinearLayout.LayourParams, and not a RelativeLayout.LayoutParams.

Upvotes: 8

Younes
Younes

Reputation: 51

In this case, the father is LinearLayout. So you should use:

TableLayout.LayoutParams layoutParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(20, 20, 20, 20);

Upvotes: 0

Related Questions