我在Android方面还很新,所以这可能是一个愚蠢的问题,但我还是想问一下。我有一个Activity的RelativeLayout布局,在这个布局中我有另一个布局位于屏幕底部。有时我会隐藏它或使其可见,这并不重要。是否可以使另一个布局的高度占总屏幕高度的27%?我的想法是保留屏幕上除此布局之外的其他内容。有人尝试过类似这样的操作吗?
LinearLayout
可以通过android:layout_weight
属性实现此功能。例如,下面是一个包含三个Button
的布局,分别占高度的50%,30%和20%:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Button
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="50"
android:text="@string/fifty_percent"/>
<Button
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="30"
android:text="@string/thirty_percent"/>
<Button
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="20"
android:text="@string/twenty_percent"/>
</LinearLayout>
然而,您不能简单地声明布局文件中任意位置的任意小部件应占屏幕大小的任意百分比。但是您可以在Java中执行该计算,并根据需要调整小部件的LayoutParams
。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/parent_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name" />
<LinearLayout
android:id="@+id/parent_of_bottom_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentBottom="true" >
<LinearLayout
android:id="@+id/content_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="27">
//Add your content here
</LinearLayout>
</LinearLayout>