Search code examples
javaandroidxmlandroid-relativelayoutmargins

Element disappears after setting margins on RelativeLayout


I'm developing a small app as project for school, and I need to dinamically move a FAB. I have a FloatingActionButton inside a Relative layout, which is actually bottom aligned and horizontally aligned.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.pagiaro.nicola.quiz2_0.HomeActivity"
    android:id="@+id/home_rl" >

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="true"
        app:fabSize="normal"
        app:srcCompat="@drawable/ic_quiz"
        android:id="@+id/fab_inizia"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginRight="@dimen/activity_horizontal_margin"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        app:backgroundTint="@color/accentColor" />

</RelativeLayout>

The code I'm using for move it is:

   final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_inizia);

   final RelativeLayout.LayoutParams rlp_keyboard_is_open = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT,
            RelativeLayout.LayoutParams.WRAP_CONTENT);

    rlp_keyboard_is_open.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    rlp_keyboard_is_open.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

    fab.setLayoutParams(rlp_keyboard_is_open);

But with this code my FAB has not right and bottom margin. The problem comes when I add code to add margins.

    rlp_keyboard_is_open.setMargins(0, 0, R.dimen.activity_horizontal_margin, R.dimen.activity_vertical_margin);

or

    rlp_keyboard_is_open.rightMargin = R.dimen.activity_horizontal_margin;
    rlp_keyboard_is_open.bottonMargin = R.dimen.activity_vertical_margin;

If I add this code, the FAB disappear. I searched al lot for a solution, but I didn't find it. Any help? Thanks.


Solution

  • Use

    getResources().getDimension(R.dimen.activity_horizontal_margin)
    

    or

    getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin)
    

    instead of directly using R.dimen.activity_horizontal_margin as it returns the internal ID assigned to R.dimen.activity_horizontal_margin rather than the value you assigned in your XML file.