Search code examples
androidandroid-layoutcentering

How to match centering of RelativeLayout (centerInParent) and layer-list (gravity:center) as windowBackground?


I have created windowBackground using layer-list, where i center item (bitmap) by using android:gravity="center". Then i show same image, but using Relative Layout with ImageView and it is centered using android:layout_centerInParent="true". However image in relative layout is slightly higher. How to center them, so they are at same position?

Layer list as windowBackground in splash_background file:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@color/appBackground" />
    <item>
        <bitmap
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:src="@raw/splash_animated" />
    </item>
</layer-list>

Activity with this Relative layout (using the style below):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".LaunchAnimatedActivity">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@raw/splash_animated" />

</RelativeLayout>

Style:

<style name="AppTheme.FullscreenSplash" parent="AppTheme.NoActionBar">
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowBackground">@drawable/splash_background</item>
        <item name="android:windowAnimationStyle">@null</item>
</style>

Solution

  • I used this piece of code to align background image with activity image:

    val statusBar = resources.getIdentifier("status_bar_height", "dimen", "android")
    if (statusBar != 0) {
        //getting statusbar height
        val statusBarHeight = resources.getDimensionPixelSize(statusBar)
        val imageView = findViewById<ImageView>(R.id.splash_image)
        // using FrameLayout instead of RelativeLayout
        imageView.updateLayoutParams<FrameLayout.LayoutParams>
        {
            //orientation aware
            if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                leftMargin = statusBarHeight
            } else {
                topMargin = statusBarHeight
            }
        }
    }