2010-11-16 134 views
14

我有一個ImageView,我希望它的大小始終相同。如果圖像小於視圖,我希望它在視圖中居中。如果圖像大於視圖,那麼我希望它縮小比例 - 保留寬高比。ImageView是一個固定的大小,不管圖像大小

我在這過幾次嘗試自己 - 最近的一項是:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <ImageView android:id="@+id/itemImage" android:layout_width="100dp" 
      android:layout_height="100dp" android:scaleType="fitCenter" 
      android:adjustViewBounds="true" android:gravity="center" android:padding="10px" /> 
    <TextView android:id="@+id/currentLentItem" android:layout_width="wrap_content" 
       android:layout_height="wrap_content" android:padding="10px"/> 
</LinearLayout> 

缺少什麼我在這裏?

+0

您是否得到了滿意的解決方案? – nwaltham 2012-01-15 21:03:04

回答

11

嘗試使用位階類型centerInside,象下面這樣:

<?xml version="1.0" encoding="utf-8"?> 
    <RelativeLayout 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     > 
    <ImageView 
     android:id="@+id/itemImage" 
     android:layout_width="100dp" 
     android:layout_height="100dp" 
     android:layout_alignParentRight="true" 
     android:scaleType="centerInside" 
     android:gravity="right|center_vertical" 
     android:padding="10px" 
     /> 
    <TextView 
     android:id="@+id/currentLentItem" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_toLeftOf="@id/list_image" 
     android:padding="10px" 
     /> 
</RelativeLayout> 

這會導致圖像按比例縮小僅當比佈局更大,並且它會按比例縮放,以及(而fitXY縮放而不考慮方面比)。如果更小,它也會將圖像居中。

編輯:我已經更新了像你想要的東西的例子。以下是改變的要點:

•ImageView引力改爲right|center_vertical。既然你想讓它們在右邊對齊,即使它們是縱向定位圖像,使用這種重力也會允許它們。

•ImageView的對齊的RelativeLayout的

•RelativeLayout的右側設置爲wrap_content因爲它是用於一個ListView。

•添加了TextView,與父項左側對齊,其右邊緣由itemImage的左邊緣定義。

+0

謝謝你 - 它看起來更好。儘管如此,View仍然不是一個固定的大小。從上面的示例中可以看到,ImageView緊挨着一個TextView,並且它顯示在一個ListView中。我希望ImageViews的右邊緣彼此排列在一起,這樣一切都看起來整潔而統一...... – 2010-11-17 09:51:06

+0

Paul,我添加了一個可以嘗試的更新示例;這應該讓你更接近你要找的東西。 – kcoppock 2010-11-17 14:20:01

+0

謝謝。儘管如此,ImageViews的尺寸仍然不盡相同。我需要他們都是完全相同的寬度。我原以爲layout_width會設置 - 但它顯然不會... – 2010-11-17 16:43:52

10

如果圖像超過視圖大小,那麼你可以使用它的規模:

android:scaleType="fitXY" 

不會給你想要的東西,如果圖像較小。也許你可以在運行時檢測到,並以編程方式更改scaleType。

+0

有沒有辦法在這些線程上「碰撞」...? – 2010-11-22 19:26:29

+0

如何在運行時更改它? – 2012-02-11 05:43:53

+0

imageView.setScaleType(ScaleType.FIT_XY); – 2015-04-07 06:16:53