正在将 ArrayList URL 加载到 ViewHolder

Loading ArrayList URL into ViewHolder

目前,我正在通过执行以下操作将可绘制资源文件夹中的图像加载到我的 ViewHolder 中:

在我的片段中,我将 ArrayList 设置为:

private ArrayList<Category> getCategory() {
    ArrayList<Category> categories=new ArrayList<>();
    Category category;

    category = new Category(R.string.string1, R.drawable.thumb1);
    categories.add(category);

    category = new Category(R.string.string2, R.drawable.thumb2);
    categories.add(category);

    category = new Category(R.string.string3, R.drawable.thumb3);
    categories.add(category);

    category = new Category(R.string.string4, R.drawable.thumb4);
    categories.add(category);

    category = new Category(R.string.string5, R.drawable.thumb5);
    categories.add(category);

    category = new Category(R.string.string6, R.drawable.thumb6);
    categories.add(category);

    return categories;
}

这里是我上面提到的 ArrayList<Category>:

public class Category {
    private int name;
    private int image;

    public Category(int name, int image) {
        this.name = name;
        this.image = image;

    }

    public int getName() {
        return name;
    }

    public void setName(int name) {
        this.name = name;
    }

    public int getImage() {
        return image;
    }

    public void setImage(int image) {
        this.image = image;
    }
}

在我的 RecyclerView.Adapter 内部 onBindViewHolder 我通过执行以下操作将图像设置为 ViewHolder

Picasso.with(c).load(category.get(position).getImage()).into(holder.img);

以上完美运行,它将我从我的可绘制资源文件夹中选择的图像加载到我的 ViewHolder 的 ImageView 中。

我的问题:

我如何使用上面相同的逻辑从 url 而不是 drawable 加载图像。我尝试用 URL.

替换 R.drawable.thumb1

试试这个

为了从 Drawable 加载图像,您使用了 get/set 作为整数的图像。 但是为了加载 url 而不是 drawable 你必须使用 get/set as string as,

在你类别class

private String image;

public String getImage() {
    return image;
}

public void setImage(String image) {
    this.image = image;
}

请更改您的模型 class 图像数据类型为字符串 因为您当前正在将整数值传递给 Picasso.load() 它应该是字符串

Picasso.with(this)
    .load("YOUR IMAGE URL HERE")
    .placeholder(Your Drawable Resource) //this is optional the image to display while the url image is downloading
    .error(Your Drawable Resource)         //this is also optional if some error has occurred in downloading the image this image would be displayed
    .into(imageView);

让示例使用新的api 从中获取密钥来解析图像和标题 像这样制作与 APi Json Format.Something 匹配的模型 class。

    },
"bar": {
  "type": "integer"
},
"baz": {
  "type": "boolean"
}

} } 使上面 json below.I 的匹配模型 class 为新 APi 而不是上面 json.

package com.bytelogs.antarikshdemo;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class News {

    @SerializedName("status")
    @Expose
    private String status;
    @SerializedName("source")
    @Expose
    private String source;
    @SerializedName("sortBy")
    @Expose
    private String sortBy;
    @SerializedName("articles")
    @Expose
    private List<Article> articles = null;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getSource() {
        return source;
    }

    public void setSource(String source) {
        this.source = source;
    }

    public String getSortBy() {
        return sortBy;
    }

    public void setSortBy(String sortBy) {
        this.sortBy = sortBy;
    }

    public List<Article> getArticles() {
        return articles;
    }

    public void setArticles(List<Article> articles) {
        this.articles = articles;
    }

}

然后在 activity_main.xml 中声明回收器视图 像这样

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/newsList"
    tools:context="com.bytelogs.antarikshdemo.NewsActivity">

</android.support.v7.widget.RecyclerView>

然后像这样制作示例 RecyclerView 项目布局。

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_margin="10dp"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="180dp"
            android:id="@+id/newsImage"
            android:adjustViewBounds="true"
            android:scaleType="centerCrop"
            android:src="@drawable/dummy"
            />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/newsTitle"
            android:text="@string/app_name"
            android:textStyle="bold"
            android:textSize="18sp"
            android:layout_marginTop="12dp"
            android:padding="4dp"
            />


    </LinearLayout>

</android.support.v7.widget.CardView>

然后 MainActivity 检索 api 图片和标题,并将它们设置为如下所示的视图。

package com.bytelogs.antarikshdemo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class NewsActivity extends AppCompatActivity {

    public static String url = "https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=top&apiKey=<API_KEY_HERE>";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_news);

        final RecyclerView recyclerView = (RecyclerView)findViewById(R.id.newsList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                GsonBuilder gsonBuilder = new GsonBuilder();
                Gson gson = gsonBuilder.create();
                News news = gson.fromJson(response,News.class);
                recyclerView.setAdapter(new NewsAdapter(NewsActivity.this,news.getArticles()));

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);

    }
}

要获得所需的行为,正如您所说,加载图像 URL 就像您对可绘制对象所做的那样。你需要修改你的类别 class 如下

public class Category {
public int name;
public int image;

//private member string variable as urls are String type
public String imageURl;


public Category(int name, int image) {
    this.name = name;
    this.image = image;

}

//constructor overloading which will take image name and image URL 
public Category(int name, String image) {
    this.name = name;
    this.imageURl = image;

}

public int getName() {
    return name;
}

public int getImage() {
    return image;
}

public String getImageUrl() {
    return imageURl;
}

}

现在,在 getCategory() 方法中,只要您想从 URL

加载图像,就可以使用此构造函数
category = new Category(R.string.string1, "your image url");
categories.add(category);

现在要使用 Picasso 为 drawable 和 URL 加载图像需要调整,您需要检查其图像是 url(字符串类型)还是 drawable(int 类型)。

if(category.get(position).imageURl !=null){
  Picasso.with(context).load(category.get(position).imageURl).into(imageView);

}else{
 Picasso.with(c).load(category.get(position).image).into(holder.img);
}