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

Ben*_* L. 16 android imageview

我正在从网站加载导航,其中每个项目都有标题,描述和图像.我希望所有标题和描述都围绕同一轴.

我正在为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>
Run Code Online (Sandbox Code Playgroud)

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

Emm*_*uel 15

这不能在XML中完成.您必须在代码中指定大小.我会onCreate()在活动中这样做:

[编辑:添加导入,浮动表示法.]

import android.widget.LinearLayout.LayoutParams;
...
obj.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                                     LayoutParams.WRAP_CONTENT,
                                     0.25f));
Run Code Online (Sandbox Code Playgroud)

这意味着使用父母身高的100%,但父母宽度的25%.

  • 很遗憾belabor的观点,但在java'0.25'是双字面值,'0.25f'是浮点字面值.如果一个参数需要一个float(如本例所示),如果你传递一个double它就不会编译(虽然反过来确实有效,因为float可以隐式地转换为double但反之亦然).为了演示,尝试编译`public void foo(float bar){foo(0.5); }` - 在你添加'f'之前它不起作用. (4认同)