0
votes

In my application I'm using Fragments (tabs) and when I try to set the margin of a LinearLayout of the fragment layout, it doesn't work.

My layout has this RelativeLayout

...
<RelativeLayout
     android:id="@+id/calendar_activities"
     android:layout_width="fill_parent"
     android:layout_height="match_parent"
     android:layout_marginLeft="10dp">
</RelativeLayout>
...

My Fragment:

public class FragmentTabSchedule extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragmenttab1, container, false);

        RelativeLayout rl = (RelativeLayout) view.findViewById(R.id.calendar_activities);

        LinearLayout ll = new LinearLayout(inflater.getContext());
        ll.setOrientation(LinearLayout.VERTICAL);
        //ll.setPadding(60, 60, 60, 60);

        Resources r = inflater.getContext().getResources();

        int h = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP,
                60, 
                r.getDisplayMetrics()
        );

        LayoutParams params = new LayoutParams(
                LayoutParams.MATCH_PARENT,      
                h
        );
        params.setMargins(60, 60, 60, 60);
        ll.setLayoutParams(params);

        ll.setBackgroundColor(getResources().getColor(R.color.yellow));

        TextView act = new TextView(inflater.getContext());

        act.setText("Activity test");
        ll.addView(act);

        rl.addView(ll);



        return view;
    }

}

The Linearlayout is created correctly, the only thing that doesn't work is the margin (already tried padding with no success). The layout is placed with 0 margin.

When I try to create the code directly in the xml file, it works

       <RelativeLayout 
            android:id="@+id/calendar_activities"
            android:layout_width="fill_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="10dp">

            <LinearLayout 
                android:layout_width="fill_parent"
                android:layout_height="60dp"
                android:orientation="vertical"
                android:layout_marginTop="120dp"
                android:background="@color/blue">

                <TextView 
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="test"/>

            </LinearLayout>

        </RelativeLayout>
1
Instead of using LayoutParams try using RelativeLayout.LayoutParams ... - maaz
Yeah, thanks @maaz, it worked - MiguelDuque
I have posted the answer, accept it please - maaz

1 Answers

1
votes

The way it works is Layout params that one should be using should be from its parent ...

In your case LinearLayout was inside RelativeLayout so, one should be using RelativeLayout.LayoutParams for the purpose