FrameLayout margin not working

Solution 1:

I had the same issue myself and noticed that setting the layout_ margins does not work until you also set your ImageView's layout gravity i.e. android:layout_gravity="top" in the XML resource file, or from code: FrameLayout.LayoutParams.gravity = Gravity.TOP;.

Solution 2:

To make it more clear why. The FrameLayout.onLayout() call contains this (in api v2.3.4 at least):

    // for each child
    final LayoutParams lp = (LayoutParams) child.getLayoutParams();
    final int gravity = lp.gravity;
    if (gravity != -1) {
        // handle all margin related stuff

So if gravity is -1, there will be no margin calculation. And the thing is, gravity in FrameLayout.LayoutParams is defined by:

    gravity = a.getInt(com.android.internal.R.styleable.FrameLayout_Layout_layout_gravity, -1);

So if gravity is not set, there will be no margin calculation.