Android在XML中获取屏幕尺寸

16

嘿,我有一个滚动视图从屏幕顶部到屏幕底部之前的一小段距离,因为这里是我的广告横幅的位置。由于 Google 的政策,我希望在这些元素之间(按钮和横幅之间)有一些像素。到目前为止,我使用 dp 值来设置间距。但是由于设备的差异,这会导致在某些高分辨率手机上广告和滚动视图之间有很大的间隔。这就是为什么我想要进行如下设置:

<ScrollView 
android:layout_height="(Screen_height-banner)-5px"
当然,我并没有以这种方式尝试过,因为这不是代码,但我认为它很好地总结了我计划做的事情。
非常感谢您的回答!
4个回答

5

由于XML不在运行时运行,因此您无法在XML中查询屏幕大小,您可以使用RelativeLayout并使用alignmentsmargins来实现此目的。

在您的情况下,如果Screen_height-banner表示屏幕高度,并且您想将其定位在底部并从末尾创建5dp分隔符,则您的XML应如下所示:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

        <ScrollView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginBottom="5dp">

</RelativeLayout >

如果你需要缩放滚动视图而不是定位它,则 xml 应该是:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding_bottom="5dp">

        <ScrollView 
            android:layout_width="wrap_content"
            android:layout_height="fill_parent">

</RelativeLayout >

2
API级别8及以上已将“fill_parent”替换为“match_parent”。 - Antonin

4

您可以使用weight参数。如果您将两个布局的权重设置为0.5,那么这将使这些布局共享屏幕宽度相等。

 <LinearLayout
    android:id="@+id/alt_panel"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/orta_panel" >

    <LinearLayout
        android:id="@+id/altsol_panel"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="0.5"
        android:gravity="center_horizontal"
        android:orientation="vertical" >


    </LinearLayout>

    <LinearLayout
        android:id="@+id/altsag_panel"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_weight="0.5"
        android:gravity="center_horizontal"
        android:orientation="vertical" >


    </LinearLayout>
</LinearLayout>

2
使用RelativeLayout,设置5px的Margin,并使用layout_above属性。

0
如果以下代码对您无效,您可能正在使用更新版本的某些内容,您可以尝试使用 android:bottom="80dp" 替代 android:layout_marginBottom="5dp"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接