将ImageView的最大宽度设置为其父容器宽度的百分比

16

我正在从一个网站加载导航,其中每个项目都有标题、描述和图像。我希望所有的标题和描述都沿着同一轴线居中。

我在ListView中为每个项目使用以下布局。当图像的宽度是高度的一半时,它可以正常工作,但如果它们更宽,则文本会出现在图像下面。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:orientation="horizontal">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1">
            <TextView
                android:layout_height="wrap_content"
                android:textSize="10pt"
                android:id="@+id/title"
                android:gravity="center_horizontal"
                android:layout_width="fill_parent" />
            <TextView
                android:layout_height="wrap_content"
                android:id="@+id/description"
                android:layout_width="fill_parent"
                android:gravity="center_horizontal" />
        </LinearLayout>
        <View
            android:layout_height="fill_parent"
            android:layout_width="fill_parent"
            android:layout_weight="3" />
    </LinearLayout>
    <ImageView
        android:id="@+id/icon"
        android:adjustViewBounds="true"
        android:layout_width="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_height="wrap_content" />
</RelativeLayout>

是否可以强制图像保持在RelativeLayout宽度的25%或更少?

1个回答

16

XML中无法完成此操作,您需要在代码中指定大小。我会在活动的onCreate()方法中完成此操作:

import android.widget.LinearLayout.LayoutParams;
...
obj.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                                     LayoutParams.WRAP_CONTENT,
                                     0.25f));

这意味着使用父元素高度的100%,但使用父元素宽度的25%


我认为这应该是LinearLayout.LayoutParams,而0.25必须为0.25f才能正常工作。 - thomas88wp
@thomas88wp 显然,这段代码需要导入LinearLayout.LayoutParams。此外,在Java中,0.25和0.25f是相同的,因为它们都有小数点。 - Emmanuel
4
抱歉再次强调一下,在Java中,'0.25'是一个双精度字面量,而'0.25f'是一个单精度字面量。如果参数需要一个单精度浮点数(如在这个例子中),如果你传递一个双精度浮点数,它将无法编译(尽管反过来可以,因为单精度可以被隐式转换为双精度,但反之则不行)。为了示范,试着编译 public void foo(float bar) { foo(0.5); } - 它不会工作,直到你添加 'f'。 - thomas88wp
但是这样仍然将其宽度设置为它的宽度,而不是最大宽度 =( - cherry-wave

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