Search code examples
androidbuttonalignmentandroid-relativelayoutvisibility

Change button alignment of buttonA when buttonB is GONE


I have placed two buttons prev and next in a RelativeLayout. When I reach the last page of my app, I am disabling the next button using :

next.setVisibility(View.GONE);

The alignment of prev button is disrupted. I want it to be aligned to the centre of the RelativeLayout, as if there was only one button.

Here is my code :

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:layout_below="@+id/radgroup"
    >
    <Button
        android:layout_marginTop="14dp"
        android:layout_marginLeft="20dp"
        android:text="@string/previous"
        android:textAllCaps="false"
        android:textSize="23dp"
        android:layout_width="150dp"
        android:layout_height="70dp"
        android:id="@+id/prev"
        android:onClick="viewPreviousQuestion"
        />
    <Button
        android:layout_marginTop="14dp"
        android:layout_marginLeft="20dp"
        android:text="@string/previous"
        android:textAllCaps="false"
        android:textSize="23dp"
        android:layout_width="150dp"
        android:layout_height="70dp"
        android:layout_toRightOf="@+id/prev"
        android:id="@+id/nxt"
        android:onClick="viewNextQuestion"
        />

</RelativeLayout>

and the onClick event is

public void viewNextQuestion(View view) {
    if(currqstn==lastqstn){
        next.setVisibility(View.GONE);
    }
}

Solution

  • Don't use a Relative Layout here,Use a Linear Layout Instead. Since in a Relative layout Views are positioned with respect to one another, when you remove one view,it might disrupt other views that were positioned with respect to the deleted view.

    EDIT

    Use can use the following attributes for your views: weightSum, weight and padding.