我们已经看到在Android中使用我们的应用程序中的简单数据实现RecyclerView。在本文中,我们将了解Android中类似Custom RecyclerView的Instagram的实现。
我们将在本文中构建什么?
我们将构建一个简单的应用程序,其中将显示Instagram个人资料中的数据,并且将使用官方的Instagram API从用户的Instagram个人资料中加载数据并在自定义RecyclerView中显示该数据。下面给出了一个示例GIF,以了解我们将在本文中做些什么。注意,我们将使用Java语言实现该项目。
分步实施
步骤1:创建一个新项目
要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。
步骤2:在您的build.gradle文件中添加以下依赖项
以下是Volley的依赖关系,我们将使用它们来从API获取数据。要添加此依赖关系,请导航至应用程序> Gradle脚本> build.gradle(app),然后在“依赖关系”部分添加以下依赖关系。
// dependancy for loading data from json file.
implementation ‘com.android.volley:volley:1.1.1’
// dependancy for loading image from url.
implementation ‘com.squareup.picasso:picasso:2.71828’
// dependancy for creating a circle image.
implementation ‘de.hdodenhof:circleimageview:3.1.0’
步骤3:创建API,以获取用于生成API的数据
现在,为Instagram帖子创建基本的显示API,我们将创建一个用于显示此数据的API。您可以参考如何在Android中为公共Instagram提要生成API URL?现在,我们使用访问令牌创建了URL,并将使用该URL获取JSON数据。
步骤4:在AndroidManifest.xml文件中添加Internet权限
当我们从互联网上加载数据时。为此,我们必须将Internet权限添加到我们的AndroidManifest.xml文件中。导航至应用程序> AndroidManifest.xml文件,然后将以下代码添加到其中。
XML
XML
XML
Java
public class InstaModal {
// variables for storing data
// of our recycler view item
private String id;
private String media_type;
private String permalink;
private String media_url;
private String username;
private String caption;
private String timestamp;
public String getAuthor_url() {
return author_url;
}
public void setAuthor_url(String author_url) {
this.author_url = author_url;
}
public int getLikesCount() {
return likesCount;
}
public void setLikesCount(int likesCount) {
this.likesCount = likesCount;
}
private String author_url;
private int likesCount;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMedia_type() {
return media_type;
}
public void setMedia_type(String media_type) {
this.media_type = media_type;
}
public String getPermalink() {
return permalink;
}
public void setPermalink(String permalink) {
this.permalink = permalink;
}
public String getMedia_url() {
return media_url;
}
public void setMedia_url(String media_url) {
this.media_url = media_url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public InstaModal(String id, String media_type, String permalink, String media_url, String username,
String caption, String timestamp, String author_url, int likesCount) {
this.id = id;
this.media_type = media_type;
this.permalink = permalink;
this.media_url = media_url;
this.username = username;
this.caption = caption;
this.timestamp = timestamp;
this.author_url = author_url;
this.likesCount = likesCount;
}
}
Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class InstagramFeedRVAdapter extends RecyclerView.Adapter {
private ArrayList instaModalArrayList;
private Context context;
public InstagramFeedRVAdapter(ArrayList instaModalArrayList, Context context) {
this.instaModalArrayList = instaModalArrayList;
this.context = context;
}
@NonNull
@Override
public InstagramFeedRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// inflating our layout for item of recycler view item.
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.insta_feed_rv_item, parent, false);
return new InstagramFeedRVAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull InstagramFeedRVAdapter.ViewHolder holder, int position) {
InstaModal modal = instaModalArrayList.get(position);
holder.authorTV.setText(modal.getUsername());
if (modal.getMedia_type().equals("IMAGE")) {
Picasso.get().load(modal.getMedia_url()).into(holder.postIV);
}
holder.desctv.setText(modal.getCaption());
holder.likeTV.setText("" + modal.getLikesCount() + " likes");
Picasso.get().load(modal.getAuthor_url()).into(holder.authorIV);
}
@Override
public int getItemCount() {
return instaModalArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView authorIV;
private TextView authorTV;
private ImageView postIV;
private TextView likeTV, desctv;
public ViewHolder(@NonNull View itemView) {
super(itemView);
authorIV = itemView.findViewById(R.id.idCVAuthor);
authorTV = itemView.findViewById(R.id.idTVAuthorName);
postIV = itemView.findViewById(R.id.idIVPost);
likeTV = itemView.findViewById(R.id.idTVLikes);
desctv = itemView.findViewById(R.id.idTVPostDesc);
}
}
}
Java
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
// creating variables for our requestqueue,
// array list, progressbar, edittext,
// image button and our recycler view.
private RequestQueue mRequestQueue;
private ArrayList instaModalArrayList;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing our views.
progressBar = findViewById(R.id.idLoadingPB);
instaModalArrayList = new ArrayList<>();
// calling method to load
// data in recycler view.
getInstagramData();
}
private void getInstagramData() {
// below line is use to initialize the variable for our request queue.
mRequestQueue = Volley.newRequestQueue(MainActivity.this);
// below line is use to clear cache this will
// be use when our data is being updated.
mRequestQueue.getCache().clear();
// below is the url for getting data
// from API in json format.
String url = "Enter your URL";
// below line we are creating a new request queue.
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
progressBar.setVisibility(View.GONE);
try {
JSONArray dataArray = response.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
// below line is to extract data from JSON file.
JSONObject dataObj = dataArray.getJSONObject(i);
String id = dataObj.getString("id");
String media_type = dataObj.getString("media_type");
String permalink = dataObj.getString("permalink");
String media_url = dataObj.getString("media_url");
String username = dataObj.getString("username");
String caption = dataObj.getString("caption");
String timestamp = dataObj.getString("timestamp");
// below line is to add a constant author image URL to our recycler view.
String author_url = "https://instagram.fnag5-1.fna.fbcdn.net/v/t51.2885-19/s320x320/75595203_828043414317991_4596848371003555840_n.jpg?_nc_ht=instagram.fnag5-1.fna.fbcdn.net&_nc_ohc=WzA_n4sdoQIAX9B5HWJ&tp=1&oh=05546141f5e40a8f02525b497745a3f2&oe=6031653B";
int likesCount = 100 + (i * 10);
// below line is use to add data to our modal class.
InstaModal instaModal = new InstaModal(id, media_type, permalink, media_url, username, caption, timestamp, author_url, likesCount);
// below line is use to add modal
// class to our array list.
instaModalArrayList.add(instaModal);
// below line we are creating an adapter class and adding our array list in it.
InstagramFeedRVAdapter adapter = new InstagramFeedRVAdapter(instaModalArrayList, MainActivity.this);
RecyclerView instRV = findViewById(R.id.idRVInstaFeeds);
// below line is for setting linear layout manager to our recycler view.
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false);
// below line is to set layout manager to our recycler view.
instRV.setLayoutManager(linearLayoutManager);
// below line is to set adapter
// to our recycler view.
instRV.setAdapter(adapter);
}
} catch (JSONException e) {
// handling error case.
e.printStackTrace();
Toast.makeText(MainActivity.this, "Fail to get Data.." + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// handling error message.
Toast.makeText(MainActivity.this, "Fail to get Data.." + error, Toast.LENGTH_SHORT).show();
}
});
queue.add(jsonObjectRequest);
}
}
步骤5:使用activity_main.xml文件
导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。
XML格式
第6步:创建一个新的布局文件以显示RecyclerView的每个项目
导航到应用程序> res>布局>右键单击它>新建>布局资源文件,并将文件命名为insta_feed_rv_item,然后将以下代码添加到其中。
XML格式
第7步:创建模态类以存储Feed的数据
导航到应用程序> Java >应用程序的包名称>右键单击它>新建> Java类,并将您的类命名为InstaModal 。
Java
public class InstaModal {
// variables for storing data
// of our recycler view item
private String id;
private String media_type;
private String permalink;
private String media_url;
private String username;
private String caption;
private String timestamp;
public String getAuthor_url() {
return author_url;
}
public void setAuthor_url(String author_url) {
this.author_url = author_url;
}
public int getLikesCount() {
return likesCount;
}
public void setLikesCount(int likesCount) {
this.likesCount = likesCount;
}
private String author_url;
private int likesCount;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMedia_type() {
return media_type;
}
public void setMedia_type(String media_type) {
this.media_type = media_type;
}
public String getPermalink() {
return permalink;
}
public void setPermalink(String permalink) {
this.permalink = permalink;
}
public String getMedia_url() {
return media_url;
}
public void setMedia_url(String media_url) {
this.media_url = media_url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public InstaModal(String id, String media_type, String permalink, String media_url, String username,
String caption, String timestamp, String author_url, int likesCount) {
this.id = id;
this.media_type = media_type;
this.permalink = permalink;
this.media_url = media_url;
this.username = username;
this.caption = caption;
this.timestamp = timestamp;
this.author_url = author_url;
this.likesCount = likesCount;
}
}
第8步:创建一个Adapter类,以将该数据设置为RecyclerView的每个项目
导航到应用程序> Java >应用程序的程序包名称>右键单击它> New Java类,并将其命名为InstagramFeedRVAdapter,然后将以下代码添加到其中。
Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class InstagramFeedRVAdapter extends RecyclerView.Adapter {
private ArrayList instaModalArrayList;
private Context context;
public InstagramFeedRVAdapter(ArrayList instaModalArrayList, Context context) {
this.instaModalArrayList = instaModalArrayList;
this.context = context;
}
@NonNull
@Override
public InstagramFeedRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
// inflating our layout for item of recycler view item.
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.insta_feed_rv_item, parent, false);
return new InstagramFeedRVAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull InstagramFeedRVAdapter.ViewHolder holder, int position) {
InstaModal modal = instaModalArrayList.get(position);
holder.authorTV.setText(modal.getUsername());
if (modal.getMedia_type().equals("IMAGE")) {
Picasso.get().load(modal.getMedia_url()).into(holder.postIV);
}
holder.desctv.setText(modal.getCaption());
holder.likeTV.setText("" + modal.getLikesCount() + " likes");
Picasso.get().load(modal.getAuthor_url()).into(holder.authorIV);
}
@Override
public int getItemCount() {
return instaModalArrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView authorIV;
private TextView authorTV;
private ImageView postIV;
private TextView likeTV, desctv;
public ViewHolder(@NonNull View itemView) {
super(itemView);
authorIV = itemView.findViewById(R.id.idCVAuthor);
authorTV = itemView.findViewById(R.id.idTVAuthorName);
postIV = itemView.findViewById(R.id.idIVPost);
likeTV = itemView.findViewById(R.id.idTVLikes);
desctv = itemView.findViewById(R.id.idTVPostDesc);
}
}
}
步骤9:使用MainActivity。 Java文件
转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。
Java
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
// creating variables for our requestqueue,
// array list, progressbar, edittext,
// image button and our recycler view.
private RequestQueue mRequestQueue;
private ArrayList instaModalArrayList;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initializing our views.
progressBar = findViewById(R.id.idLoadingPB);
instaModalArrayList = new ArrayList<>();
// calling method to load
// data in recycler view.
getInstagramData();
}
private void getInstagramData() {
// below line is use to initialize the variable for our request queue.
mRequestQueue = Volley.newRequestQueue(MainActivity.this);
// below line is use to clear cache this will
// be use when our data is being updated.
mRequestQueue.getCache().clear();
// below is the url for getting data
// from API in json format.
String url = "Enter your URL";
// below line we are creating a new request queue.
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
progressBar.setVisibility(View.GONE);
try {
JSONArray dataArray = response.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
// below line is to extract data from JSON file.
JSONObject dataObj = dataArray.getJSONObject(i);
String id = dataObj.getString("id");
String media_type = dataObj.getString("media_type");
String permalink = dataObj.getString("permalink");
String media_url = dataObj.getString("media_url");
String username = dataObj.getString("username");
String caption = dataObj.getString("caption");
String timestamp = dataObj.getString("timestamp");
// below line is to add a constant author image URL to our recycler view.
String author_url = "https://instagram.fnag5-1.fna.fbcdn.net/v/t51.2885-19/s320x320/75595203_828043414317991_4596848371003555840_n.jpg?_nc_ht=instagram.fnag5-1.fna.fbcdn.net&_nc_ohc=WzA_n4sdoQIAX9B5HWJ&tp=1&oh=05546141f5e40a8f02525b497745a3f2&oe=6031653B";
int likesCount = 100 + (i * 10);
// below line is use to add data to our modal class.
InstaModal instaModal = new InstaModal(id, media_type, permalink, media_url, username, caption, timestamp, author_url, likesCount);
// below line is use to add modal
// class to our array list.
instaModalArrayList.add(instaModal);
// below line we are creating an adapter class and adding our array list in it.
InstagramFeedRVAdapter adapter = new InstagramFeedRVAdapter(instaModalArrayList, MainActivity.this);
RecyclerView instRV = findViewById(R.id.idRVInstaFeeds);
// below line is for setting linear layout manager to our recycler view.
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this, RecyclerView.VERTICAL, false);
// below line is to set layout manager to our recycler view.
instRV.setLayoutManager(linearLayoutManager);
// below line is to set adapter
// to our recycler view.
instRV.setAdapter(adapter);
}
} catch (JSONException e) {
// handling error case.
e.printStackTrace();
Toast.makeText(MainActivity.this, "Fail to get Data.." + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// handling error message.
Toast.makeText(MainActivity.this, "Fail to get Data.." + error, Toast.LENGTH_SHORT).show();
}
});
queue.add(jsonObjectRequest);
}
}
现在运行您的应用程序,并查看该应用程序的输出。
输出:
在以下链接上查看项目: https : //github.com/ChaitanyaMunje/LibraryApp/tree/InstagramCustomListVIew