2010-06-11 100 views
14

我从网站加载导航,其中每个项目都有标题,说明和图像。我希望所有的标题和描述都集中在同一个轴上。将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> 

是否有可能迫使形象留在RelativeLayout的的宽度或更低的25%?

回答

15

这不能在XML中完成。你将不得不在代码中指定大小。我会做的是,在活动的onCreate()

[编辑:增加进口,浮动符号]

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

这意味着使用父母的高度的100%,但母公司的宽度的25% 。

+0

我相信这必须是LinearLayout.LayoutParams,并且0.25必须是0.25f才能工作。 – thomas88wp 2012-12-27 17:33:32

+0

@ thomas88wp显然这段代码需要导入LinearLayout.LayoutParams。另外,由于小数点的原因,0.25和0.25f在Java中是一样的。 – Emmanuel 2013-01-08 21:17:47

+4

抱歉,要点,但在Java'0.25'是一个双重字面值,'0.25f'是一个浮点数字。如果一个参数需要一个浮点数(在这种情况下),如果您将其传递给double,它将不会编译(尽管其他方式可以工作,因为float可以隐式转换为double而不是反之亦然)。为了演示,试着编译'public void foo(float bar){foo(0.5); '' - 直到你添加'f'才会起作用。 – thomas88wp 2013-01-20 18:59:53