如何将 Glide 与 GridView 一起使用? (Android/Kotlin)

How do I use Glide with GridView? (Android/Kotlin)

我已经使用此代码成功构建了一个 gridView

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {

    var inflater = mContext!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    var row = inflater.inflate(R.layout.image_cell, null)  

    row!!.glide_img_cell_id.setImageResource(R.drawable.cookie_icon_60)

    return row
}

它 returns 测试图像应该在 gridView 但是,我的真实图像数据来自 urls,所以我使用的是 Glide。我已经使用 Glide 检查了我的真实数据,它工作正常。但是,我似乎无法在我的 GridView 中使用它。这是我修改过的代码:

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {

    var recipe = this.recipeArray!![position].recipeImage
    var inflater = mContext!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    var row = inflater.inflate(R.layout.image_cell, null)  

    row!!.glide_img_cell_id.loadImageUrl(recipe) as GlideImageView

    return row
}

除了我现在使用 Glide,我也在做同样的事情。另外,我感到困惑的另一件事是 convertView。我看过的一些教程使用它,其他的则没有。它是什么?显然我在第一个示例中不需要它,因为它有效。

更新 投射到 GlideImageView 应用程序崩溃 kotlin.Unit cannot be cast to com.bumptech.glide.Glide,不投射它根本不显示任何内容。

UPDATE2 按照建议,我将代码更改为以下内容,但应用程序仍然是空白的,没有任何显示:

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
    var recipe = this.recipeArray!![position].recipeImage

    var inflater = mContext!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    var row = inflater.inflate(R.layout.image_cell, null)  
    Glide.with(mContext).load(recipe).fitCenter().centerCrop().into(row!!.glide_img_cell_id)

    return row
}

这看起来对吗?

更新 还是没有解决这个问题。查看了应该包含图像的 xml 文件。看起来像这样:

<?xml version="1.0" encoding="utf-8"?>

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/glide_img_cell_id"
    android:layout_centerInParent="true"
    android:scaleType="centerCrop"
    />

也使用了 <com.master.glideimageview.GlideImageView 而不是 <ImageView 但仍然没有。

也试过这个:

override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
    var recipe = this.recipeArray!![position].recipeImage

    var cv = convertView
    var test = LayoutInflater.from(mContext)
    cv = test.inflate(R.layout.image_cell, parent, false)

    Glide.with(this.mContext).load(recipe).into(cv!!.glide_img_cell_id as ImageView)

    return cv
}

...这很相似。但这也不管用。不知道为什么它不起作用...

在您的适配器中使用此代码。

Glide.with(context)
                .load(url)
                .fitCenter()
                .centerCrop()
                .into(imageview);

希望对你有所帮助

Glide.with(this).load(recipe).into(row!!.glide_img_cell_id)

好的,现在解决了:改用 Picasso。做了完全一样的事情。 :/