2013-03-16 111 views
1

我有一个GridView,我用它来显示一行4个图像,每个图像是200 x 200像素。这里是布局的xml:GridView拉伸ImageView非均匀

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".MainActivity" > 

    <GridView 
     android:id="@+id/myGridView" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentTop="true" 
     android:numColumns="4" > 
    </GridView> 

</RelativeLayout> 

当我跑这里来了我的应用程序的图片是什么样子:

grid view with 4 images

正如你所看到的图像越来越缩小(缩小),以适应屏幕。

我该如何使图像在垂直和水平方向拉伸以保持正确的高宽比?

请注意,我使用的是适配器图像:

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    ImageView imageView; 
    if (convertView == null) { 
     imageView = new ImageView(context); 
    } else { 
     imageView = (ImageView) convertView; 
    } 
    imageView.setBackgroundResource(imageIds[position]); 
    return imageView; 
} 
+1

你试图起诉imageView.setImageResource而不是setBackgroundResource? – sandrstar 2013-03-16 03:52:42

回答

3

我得到了同样的问题,在过去的weak.Use我的图像视图类和解决这个问题。

public class iv_autoSizedImageView extends ImageView { 

    public iv_autoSizedImageView(Context context, AttributeSet attrs) { 
     super(context, attrs); 

    } 

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 

     // TODO Auto-generated method stub 
     super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
     try { 

      getLayoutParams().height = getMeasuredWidth(); 

     } catch (Exception e) { 
      // TODO: handle exception 

     } 

    } 

} 

layout.xml

<com.sample.test.iv_autoSizedImageView 
      android:id="@+id/IV_NEWS_IMAGE" 
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent"/>