居中图像相对于屏幕的视图(忽略状态栏和导航栏)



我正在使用 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 - 但是,我有文章解释的"跳跃问题",但在某种程度上作者可能没有预料到。

解释一下:当应用程序首次打开时,启动活动上会显示一个基于图层列表的初始屏幕,当应用程序加载到内存中时,该屏幕将传输到反应本机初始屏幕活动(由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>

您可以使用如下所示以编程方式偏移启动屏幕

@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;
}

最新更新