Search code examples
androidandroid-layoutmarginfloating-action-buttonandroid-layoutparams

How to increase layout_marginBottom by a number of pixels?


In a game I display a custom View and a FAB in a FrameLayout:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <de.slova.GameView
        android:id="@+id/gameView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_marginBottom="16dp"
        android:layout_marginRight="16dp"
        android:src="@drawable/play_white" />

</FrameLayout>

However the FAB is shown too low and obscures the light blue bar at the bottom:

screenshot

I need to increase the layout_marginBottom by the height of the light blue bar (indicated by the red arrows at the above screenshot), so that the FAB is moved up.

I do know the height of the bar in pixels (the content of my custom View is scaled by a Matrix) and I think I know the right place for this action (the onSizeChanged method in my custom View) - but my difficulty is getting ahold of the FAB's layout_marginBottom value.

How to access and change it please? I have tried:

@Override
protected void onSizeChanged(int w, int h, int oldW, int oldH) {
    super.onSizeChanged(w, h, oldW, oldH);

    int h = mBar.getHeight();

    ViewGroup.LayoutParams params = mFab.getLayoutParams();

    // how to add h to layout_marginBottom here?

    mFab.setLayoutParams(params);
}

By the way I do have two methods to translate between dp and px if needed here:

public static float px2sp(Context context, float px) {
    float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
    return px / scaledDensity;
}

public static float sp2px(Context context, float sp) {
    float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
    return sp * scaledDensity;
}

Solution

  • Margin property is part of FrameLayout.LayoutParams Class, so you have to cast it to FrameLayout.LayoutParams

    FrameLayout.LayoutParams param = (FrameLayout.LayoutParams) fab.getLayoutParams();
    param.bottomMargin = mBar.getHeight();
    fab.setLayoutParams(param);