【问题标题】:Set ImageView's max width as a percent of its parent's width将 ImageView 的最大宽度设置为其父宽度的百分比
【发布时间】:2011-03-02 18:55:53
【问题描述】:

我正在从一个网站加载导航,其中每个项目都有一个标题、描述和图像。我想让所有的标题和描述都集中在同一个轴上。

我为 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% 或更小?

【问题讨论】:

    标签: android imageview


    【解决方案1】:

    这不能在 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 显然这段代码需要导入LinearLayout.LayoutParams。此外,由于小数点,0.25 和 0.25f 在 Java 中是相同的。
    • 很抱歉,在java中'0.25'是一个双精度字,而'0.25f'是一个浮点字面量。如果一个参数需要一个浮点数(如本例所示),如果你将它传递给一个双精度参数,它将无法编译(尽管反过来也可以,因为浮点数可以隐式转换为双精度浮点数,反之亦然)。为了演示,请尝试编译 public void foo(float bar) { foo(0.5); } - 在添加“f”之前它不会工作。
    • 但这无论如何都会设置宽度。不是最大宽度 =(
    猜你喜欢
    • 2019-01-11
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 1970-01-01
    • 2018-08-21
    • 2015-08-11
    • 2013-03-12
    相关资源
    最近更新 更多