Set ImageView's max width as a percent of its parent's width

醉酒当歌 提交于 2019-11-26 14:24:17

问题


I'm loading navigation from a website, where each item has a title, description, and image. I want to have all of the titles and descriptions centered along the same axis.

I'm using the following layout for each item in a ListView. It works fine when the images are half as wide as they are tall, but not if they are any wider - the text goes under the image.

<?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>

Is it possible to force the image to stay at 25% of the RelativeLayout's width or less?


回答1:


This can't be done in the XML. You would have to specify the size in the code. I would do that in the onCreate() of the activity:

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

This means use 100% of the parent's height but 25% of the parent's width.



来源:https://stackoverflow.com/questions/3025048/set-imageviews-max-width-as-a-percent-of-its-parents-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!