代码之家  ›  专栏  ›  技术社区  ›  Hofma Dresu

背景中居中的元素与前景中居中的元素不匹配

  •  1
  • Hofma Dresu  · 技术社区  · 6 年前

    这就是我现在看到的。红色框由背景创建,绿色框由前景创建。屏幕截图是用nexus5xapi26模拟器创建的。 centered element mismatch example

    前台布局:

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

    背景可绘制(通过 android:windowBackground 在我的主题中)

    <?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:gravity="center">
            <shape
                android:gravity="center"
                android:shape="rectangle">
                <solid android:color="@color/background_box" />
                <size android:width="10dp"
                    android:height="10dp" />
            </shape>
        </item>
    
    </layer-list>
    

    <?xml version="1.0" encoding="utf-8"?>
    <resources>   
        ...
        <color name="background">#ffffff</color>
        <color name="background_box">#AAFF0000</color>
        <color name="foreground_box">#AA00FF00</color>
    </resources>
    

    此示例项目的完整源代码位于 https://github.com/HofmaDresu/AndroidCenteredTest

    3 回复  |  直到 6 年前
        1
  •  1
  •   Krishna Sharma    6 年前

    原因是什么 windowBackground 包括两个高度

    修改background.xml中的下一行

    <item android:gravity="center" android:top="80dp"> // 56 actionBarSize + 24 statusBarHeight
    

    这是结果。为了进行测试,将背景尺寸调整得更大一些,以便视图和背景之间的重叠变得可见。

    enter image description here

        2
  •  0
  •   Sajal Narang    6 年前

    这可能是因为 ActionBar 在前景。

    View 在前台布局中:

    android:layout_marginBottom="?android:attr/actionBarSize"
    
        3
  •  0
  •   Devster - Angelo Cimino    6 年前

    <?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:gravity="center" android:bottom="48dp">
        <shape
            android:gravity="center"
            android:shape="rectangle">
            <solid android:color="@color/background_box" />
            <size
                android:width="10dp"
                android:height="10dp" />
        </shape>
    </item>
    

    使用 android:bottom 而不是中心背景。根据我的测试结果,48dp是正确的值。