如何通过多个像素增加layout_marginBottom?

时间:2017-10-07 08:38:21

标签: android android-layout margin floating-action-button android-layoutparams

在游戏中,我在FrameLayout中显示自定义视图和FAB:

<?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>

然而,FAB显示得太低并且遮挡了底部的浅蓝色条:

screenshot

我需要将layout_marginBottom增加浅蓝色条的高度(由上面屏幕截图中的红色箭头指示),以便FAB向上移动。

我知道条形图的高度(以像素为单位)(我的自定义视图的内容由矩阵缩放)我认为我知道此操作的正确位置(我的自定义视图中的onSizeChanged方法) - 但我的困难在于获得FAB的layout_marginBottom价值。

如何访问和更改它?我试过了:

@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);
}

顺便说一下,如果需要,我有两种方法可以在dppx之间进行翻译:

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;
}

1 个答案:

答案 0 :(得分:1)

保证金属性是FrameLayout.LayoutParams类的一部分,因此您必须将其强制转换为FrameLayout.LayoutParams

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