android - GridView 不均匀地拉伸(stretch) ImageView

标签 android gridview imageview stretch

我有一个 GridView,我用它来显示一行 4 张图像,每张图像都是 200 x 200 像素。这是布局 xml:

<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

如您所见,图像正在缩放(变窄)以适合屏幕。

如何使图像垂直和水平拉伸(stretch)以保持正确的纵横比?

请注意,我正在使用适配器绘制图像:

@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;
}

最佳答案

我在 last weak 中遇到了同样的问题。使用我的 ImageView 类来解决这个问题。

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"/>

关于android - GridView 不均匀地拉伸(stretch) ImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15444743/

相关文章:

android - 使用 Picasso 和 Glide 获取黑色 ImageView

android - 在Mifare DESFire卡上格式化PICC使其无用?

c# - 我的 gridview 中有 SQL Insert 问题

android - 将图像从 ImageView 保存到设备图库

css - 将 GridView 添加按钮移到删除按钮的右侧?

gridview - 如何在yii2中的GridView中设置页面大小

android - 从 ImageView 获取资源 ID

java - Kotlin-android : unresolved reference databinding

android - 如何在 Android 中获取原始 map 标记图标?

android - 如何在两列上创建带有正方形项目的 GridView?