在LinearLayout中使用layout_weight和ImageView

4

我正在尝试将一个ImageView放置在屏幕中央,然后在它的上下方放置其他视图,因此我决定使用一个LinearLayout(垂直)和一个LinearLayout(水平)。但是,当我为ImageView使用layout_weight时,图像完全消失了(显示一个空白屏幕)。ImageView的图像是在onCreate()中设置的。我希望ImageView占据屏幕宽度的50%,因此我使用了权重。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:orientation="vertical">

<View
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"/>

<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="horizontal"
android:layout_weight="2">

<View android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"/>

    <ImageView android:layout_weight="2" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/albumArtImageView"></ImageView>

    <View android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"/>

</LinearLayout>
<View
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1"/>
</LinearLayout>
2个回答

5
为了使layout_weight有用,需要有剩余空间。你的顶部LinearLayout下的第一个视图具有layout_height="fill_parent"。这占用了所有空间。尝试在你想要由layout_weight确定维度的地方设置layout_height="0dp",我认为你的结果会更好。

当我尝试设置layout_height="0"时,显然我不允许使用整数类型。 - Alex
哦,我总是犯那个错误。我正在更正我的答案,以便其他人也不会被绊倒。 - Ted Hopp

-1
尝试将第二个线性布局的方向更改为垂直。

那么这将不会导致ImageView两侧有空隙,对吧?但这并不是我在这种情况下想要的。 - Alex

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