Search code examples
androidpaddingtoolbarstatusbar

Android ViewGroup Incorrectly Shifts Up After Navigating Back


I am trying to figure out why my view appears to shift up after returning to an activity's screen.

Here is the image before navigating away to another fragment.

enter image description here

Here is the image after navigating back to original screen:

enter image description here

The xml file of the activity is:

<layout
    <androidx.constraintlayout.widget.ConstraintLayout
      <androidx.appcompat.widget.Toolbar
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       app:layout_constraintTop_toTopOf="parent"
      />
      <androidx.constraintlayout.widget.ConstraintLayout
         .
         .
         .
      </androidx.constraintlayout.widget.ConstraintLayout>
      .
      .
      .
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

Note that I cannot use fitsSystemWindows=true because I don't want to create a border at the top of the toolbar, the UI should have a continuous white background from behind the status bar. Also, there is no keyboard present on the screen to cause this shift.


Solution

  • What worked for me was adding android:fitsSystemWindows="true" within the Toolbar tag itself i.e

     <androidx.constraintlayout.widget.ConstraintLayout
          <androidx.appcompat.widget.Toolbar
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           app:layout_constraintTop_toTopOf="parent"
           android:fitsSystemWindows="true"
          />
    

    Adding this tag to the root layout created a boundary in the toolbar which I was trying to avoid. Setting android:windowTranslucentStatus was not necessary in my case and did not affect the layout.