相对于屏幕的中心ImageView(忽略状态栏和导航栏)

时间:2018-06-19 07:32:04

标签: android layout

我正在使用react原生启动画面包(https://github.com/crazycodeboy/react-native-splash-screen),并尝试在Android中实现正确的启动画面,其中会显示徽标。

我最初发现这篇文章,它很好地涵盖了它:https://medium.com/handlebar-labs/how-to-add-a-splash-screen-to-a-react-native-app-ios-and-android-30a3cec835ae - 然而,我有文章解释的“跳跃问题”,但作者可能没想到。

让我们解释一下:当应用程序首次打开时,启动活动会显示基于图层列表的启动画面,当应用程序转移到react-native-splash-screen活动(由launch_screen.xml定义)时已加载到内存中。问题是,虽然启动活动的主题填满整个屏幕,但launch_screen.xml中定义的启动画面的第二阶段确实关心布局。因此,“居中徽标”向上或向下偏移24dp,具体取决于Android设备是否具有软导航按钮。

如果它是一个恒定的偏移量,我只是使用边距来抵消徽标,但是由于导航按钮,我需要在xml中使用某种条件,它可以检测并对现有的导航栏作出反应

因此,我想在屏幕中心对齐ImageView,而不是其父容器。那个,或者让父容器以某种方式存在于导航栏下面。

或者,换句话说,问题是第一阶段的相对于屏幕的中心,而第二阶段相对于屏幕的可用空间,我我希望能够以某种方式匹配这两者,无论导航条存在如何都可以使用

这可能吗?

代码

launch_screen.xml(第二阶段的布局)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true"
    android:background="@color/background">

    <TextView android:text="App"
         android:layout_alignParentBottom="true"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:paddingBottom="20dp"
         android:gravity="center"/>



    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">

        <ImageView
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:src="@mipmap/logo"/>

    </LinearLayout>
</RelativeLayout>

background_splash.xml(在第一阶段使用的主题)

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@color/background"/>

    <item
        android:width="200dp"
        android:height="200dp"
        android:drawable="@mipmap/logo"
        android:gravity="center"
         />

</layer-list>

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容以编程方式偏移启动屏幕

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    ImageView image = view.findViewById(R.id.image_logo);
    image.setTranslationY((getNavBarHeight() - getStatusBarHeight()) / 2.0f);

}

public int getStatusBarHeight() {
    int result = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0) {
        result = getResources().getDimensionPixelSize(resourceId);
    }
    return result;
}

public int getNavBarHeight(){
    Resources resources = getResources();
    int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
    if (resourceId > 0) {
        return resources.getDimensionPixelSize(resourceId);
    }
    return 0;
}