📜  如何在Android中构建类似于Custom RecyclerView的Facebook?

📅  最后修改于: 2021-05-08 20:18:59             🧑  作者: Mango

我们已经看到在Android中使用我们的应用程序中的简单数据实现RecyclerView。在本文中,我们将研究Facebook的实现,例如Android中的Custom RecyclerView

我们将在本文中构建什么?

我们将构建一个简单的应用程序,在其中我们将在Android应用程序中像RecyclerView一样显示Facebook。我们将从本文提供的简单API(https://jsonkeeper.com/b/OB3B)中获取此数据。借助此API,我们将在RecyclerView中显示该数据。下面给出了一个示例GIF,以了解我们将在本文中做些什么。注意,我们将使用Java语言实现该项目。

在Android示例GIF中构建类似于Custom RecyclerView的Facebook

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:在您的build.gradle文件中添加以下依赖项

以下是Volley的依赖关系,我们将使用它们来从API获取数据。要添加此依赖关系,请导航至应用程序> Gradle脚本> build.gradle(app),然后在“依赖关系”部分添加以下依赖关系。

步骤3:在您的AndroidManifest.xml文件中添加互联网权限

为此,当我们从Internet加载数据时,我们必须将Internet权限添加到我们的AndroidManifest.xml文件中。导航至应用程序> AndroidManifest.xml文件,然后将以下代码添加到其中。

XML


XML


  
    
    
  
    
    
      


XML


    
    
    
    


XML


  
    
  
        
              
            
            
  
            
                  
                
                
  
                
                
                  
            
  
        
  
  
        
        
  
        
        
  
        
        
  
            
  
                
  
                
                  
            
  
            
  
                
                  
                
            
  
            
  
                
  
                
  
            
  
        
  
    
  


Java
public class FacebookFeedModal {
    // variables for storing our author image,
    // author name, postDate,postDescription,
    // post image,post likes,post comments.
    private String authorImage;
    private String authorName;
    private String postDate;
    private String postDescription;
    private String postIV;
    private String postLikes;
    private String postComments;
      
    // creating getter and setter methods.
    public String getAuthorImage() {
        return authorImage;
    }
  
    public void setAuthorImage(String authorImage) {
        this.authorImage = authorImage;
    }
  
    public String getAuthorName() {
        return authorName;
    }
  
    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }
  
    public String getPostDate() {
        return postDate;
    }
  
    public void setPostDate(String postDate) {
        this.postDate = postDate;
    }
  
    public String getPostDescription() {
        return postDescription;
    }
  
    public void setPostDescription(String postDescription) {
        this.postDescription = postDescription;
    }
  
    public String getPostIV() {
        return postIV;
    }
  
    public void setPostIV(String postIV) {
        this.postIV = postIV;
    }
  
    public String getPostLikes() {
        return postLikes;
    }
  
    public void setPostLikes(String postLikes) {
        this.postLikes = postLikes;
    }
  
    public String getPostComments() {
        return postComments;
    }
  
    public void setPostComments(String postComments) {
        this.postComments = postComments;
    }
  
    // creating a constructor class.
    public FacebookFeedModal(String authorImage, String authorName, String postDate, 
                             String postDescription, String postIV, String postLikes, 
                             String postComments) {
        this.authorImage = authorImage;
        this.authorName = authorName;
        this.postDate = postDate;
        this.postDescription = postDescription;
        this.postIV = postIV;
        this.postLikes = postLikes;
        this.postComments = postComments;
    }
}


Java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
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 FacebookFeedRVAdapter extends RecyclerView.Adapter {
      
    // arraylist for our facebook feeds.
    private ArrayList facebookFeedModalArrayList;
    private Context context;
  
    // creating a constructor for our adapter class.
    public FacebookFeedRVAdapter(ArrayList facebookFeedModalArrayList, Context context) {
        this.facebookFeedModalArrayList = facebookFeedModalArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public FacebookFeedRVAdapter.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.facebook_feed_rv_item, parent, false);
        return new FacebookFeedRVAdapter.ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull FacebookFeedRVAdapter.ViewHolder holder, int position) {
        // getting data from array list and setting it to our modal class.
        FacebookFeedModal modal = facebookFeedModalArrayList.get(position);
          
        // setting data to each view of recyclerview item.
        Picasso.get().load(modal.getAuthorImage()).into(holder.authorIV);
        holder.authorNameTV.setText(modal.getAuthorName());
        holder.timeTV.setText(modal.getPostDate());
        holder.descTV.setText(modal.getPostDescription());
        Picasso.get().load(modal.getPostIV()).into(holder.postIV);
        holder.likesTV.setText(modal.getPostLikes());
        holder.commentsTV.setText(modal.getPostComments());
    }
  
    @Override
    public int getItemCount() {
        // returning the size of our array list.
        return facebookFeedModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our views 
        // of recycler view items.
        private CircleImageView authorIV;
        private TextView authorNameTV, timeTV, descTV;
        private ImageView postIV;
        private TextView likesTV, commentsTV;
        private LinearLayout shareLL;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our variables
            shareLL = itemView.findViewById(R.id.idLLShare);
            authorIV = itemView.findViewById(R.id.idCVAuthor);
            authorNameTV = itemView.findViewById(R.id.idTVAuthorName);
            timeTV = itemView.findViewById(R.id.idTVTime);
            descTV = itemView.findViewById(R.id.idTVDescription);
            postIV = itemView.findViewById(R.id.idIVPost);
            likesTV = itemView.findViewById(R.id.idTVLikes);
            commentsTV = itemView.findViewById(R.id.idTVComments);
        }
    }
}


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 ArrayList facebookFeedModalArrayList;
    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);
  
        // calling method to load
        // data in recycler view.
        getFacebookFeeds();
    }
  
    private void getFacebookFeeds() {
        facebookFeedModalArrayList = new ArrayList<>();
  
        // 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 stored in
        // string for our sample data
        String url = "https://jsonkeeper.com/b/OB3B";
  
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONObject response) {
                progressBar.setVisibility(View.GONE);
                try {
                    // in below line we are extracting the data from json object.
                    String authorName = response.getString("authorName");
                    String authorImage = response.getString("authorImage");
                      
                    // below line is to get json array from our json object.
                    JSONArray feedsArray = response.getJSONArray("feeds");
                      
                    // running a for loop to add data to our array list
                    for (int i = 0; i < feedsArray.length(); i++) {
                        // getting json object of our json array.
                        JSONObject feedsObj = feedsArray.getJSONObject(i);
                          
                        // extracting data from our json object.
                        String postDate = feedsObj.getString("postDate");
                        String postDescription = feedsObj.getString("postDescription");
                        String postIV = feedsObj.getString("postIV");
                        String postLikes = feedsObj.getString("postLikes");
                        String postComments = feedsObj.getString("postComments");
                          
                        // adding data to our modal class.
                        FacebookFeedModal feedModal = new FacebookFeedModal(authorImage, authorName, postDate, postDescription, postIV, postLikes, postComments);
                        facebookFeedModalArrayList.add(feedModal);
                          
                        // below line we are creating an adapter class and adding our array list in it.
                        FacebookFeedRVAdapter adapter = new FacebookFeedRVAdapter(facebookFeedModalArrayList, 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) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Fail to get data with error " + error, Toast.LENGTH_SHORT).show();
            }
        });
        mRequestQueue.add(jsonObjectRequest);
    }
}


步骤4:使用activity_main.xml文件

导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。

XML格式



  
    
    
  
    
    
      

步骤5:为我们的背景图片创建自定义可绘制文件

导航到应用程序> res> drawable>右键单击它> New> drawable资源文件,并将文件命名为background_drawable,然后将以下代码添加到其中以用于我们的自定义背景。

XML格式



    
    
    
    

步骤6:为我们的RecyclerView项目创建一个布局文件

导航到应用程序> res>布局>右键单击它>新建>布局资源文件,并将其命名为facebook_feed_rv_item并向其中添加以下代码。在代码中添加了注释,以便更详细地了解。

XML格式



  
    
  
        
              
            
            
  
            
                  
                
                
  
                
                
                  
            
  
        
  
  
        
        
  
        
        
  
        
        
  
            
  
                
  
                
                  
            
  
            
  
                
                  
                
            
  
            
  
                
  
                
  
            
  
        
  
    
  

第7步:创建用于存储数据的模式类

导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,并将您的类命名为FacebookFeedModal,然后将以下代码添加到其中。

Java

public class FacebookFeedModal {
    // variables for storing our author image,
    // author name, postDate,postDescription,
    // post image,post likes,post comments.
    private String authorImage;
    private String authorName;
    private String postDate;
    private String postDescription;
    private String postIV;
    private String postLikes;
    private String postComments;
      
    // creating getter and setter methods.
    public String getAuthorImage() {
        return authorImage;
    }
  
    public void setAuthorImage(String authorImage) {
        this.authorImage = authorImage;
    }
  
    public String getAuthorName() {
        return authorName;
    }
  
    public void setAuthorName(String authorName) {
        this.authorName = authorName;
    }
  
    public String getPostDate() {
        return postDate;
    }
  
    public void setPostDate(String postDate) {
        this.postDate = postDate;
    }
  
    public String getPostDescription() {
        return postDescription;
    }
  
    public void setPostDescription(String postDescription) {
        this.postDescription = postDescription;
    }
  
    public String getPostIV() {
        return postIV;
    }
  
    public void setPostIV(String postIV) {
        this.postIV = postIV;
    }
  
    public String getPostLikes() {
        return postLikes;
    }
  
    public void setPostLikes(String postLikes) {
        this.postLikes = postLikes;
    }
  
    public String getPostComments() {
        return postComments;
    }
  
    public void setPostComments(String postComments) {
        this.postComments = postComments;
    }
  
    // creating a constructor class.
    public FacebookFeedModal(String authorImage, String authorName, String postDate, 
                             String postDescription, String postIV, String postLikes, 
                             String postComments) {
        this.authorImage = authorImage;
        this.authorName = authorName;
        this.postDate = postDate;
        this.postDescription = postDescription;
        this.postIV = postIV;
        this.postLikes = postLikes;
        this.postComments = postComments;
    }
}

步骤8:创建一个Adapter类,用于将数据设置为我们的RecyclerView项目

导航到应用程序> Java >应用程序的程序包名称>右键单击它> New Java类,并将其命名为FacebookFeedRVAdapter,然后将以下代码添加到其中。

Java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
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 FacebookFeedRVAdapter extends RecyclerView.Adapter {
      
    // arraylist for our facebook feeds.
    private ArrayList facebookFeedModalArrayList;
    private Context context;
  
    // creating a constructor for our adapter class.
    public FacebookFeedRVAdapter(ArrayList facebookFeedModalArrayList, Context context) {
        this.facebookFeedModalArrayList = facebookFeedModalArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public FacebookFeedRVAdapter.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.facebook_feed_rv_item, parent, false);
        return new FacebookFeedRVAdapter.ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull FacebookFeedRVAdapter.ViewHolder holder, int position) {
        // getting data from array list and setting it to our modal class.
        FacebookFeedModal modal = facebookFeedModalArrayList.get(position);
          
        // setting data to each view of recyclerview item.
        Picasso.get().load(modal.getAuthorImage()).into(holder.authorIV);
        holder.authorNameTV.setText(modal.getAuthorName());
        holder.timeTV.setText(modal.getPostDate());
        holder.descTV.setText(modal.getPostDescription());
        Picasso.get().load(modal.getPostIV()).into(holder.postIV);
        holder.likesTV.setText(modal.getPostLikes());
        holder.commentsTV.setText(modal.getPostComments());
    }
  
    @Override
    public int getItemCount() {
        // returning the size of our array list.
        return facebookFeedModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our views 
        // of recycler view items.
        private CircleImageView authorIV;
        private TextView authorNameTV, timeTV, descTV;
        private ImageView postIV;
        private TextView likesTV, commentsTV;
        private LinearLayout shareLL;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our variables
            shareLL = itemView.findViewById(R.id.idLLShare);
            authorIV = itemView.findViewById(R.id.idCVAuthor);
            authorNameTV = itemView.findViewById(R.id.idTVAuthorName);
            timeTV = itemView.findViewById(R.id.idTVTime);
            descTV = itemView.findViewById(R.id.idTVDescription);
            postIV = itemView.findViewById(R.id.idIVPost);
            likesTV = itemView.findViewById(R.id.idTVLikes);
            commentsTV = itemView.findViewById(R.id.idTVComments);
        }
    }
}

步骤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 ArrayList facebookFeedModalArrayList;
    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);
  
        // calling method to load
        // data in recycler view.
        getFacebookFeeds();
    }
  
    private void getFacebookFeeds() {
        facebookFeedModalArrayList = new ArrayList<>();
  
        // 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 stored in
        // string for our sample data
        String url = "https://jsonkeeper.com/b/OB3B";
  
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONObject response) {
                progressBar.setVisibility(View.GONE);
                try {
                    // in below line we are extracting the data from json object.
                    String authorName = response.getString("authorName");
                    String authorImage = response.getString("authorImage");
                      
                    // below line is to get json array from our json object.
                    JSONArray feedsArray = response.getJSONArray("feeds");
                      
                    // running a for loop to add data to our array list
                    for (int i = 0; i < feedsArray.length(); i++) {
                        // getting json object of our json array.
                        JSONObject feedsObj = feedsArray.getJSONObject(i);
                          
                        // extracting data from our json object.
                        String postDate = feedsObj.getString("postDate");
                        String postDescription = feedsObj.getString("postDescription");
                        String postIV = feedsObj.getString("postIV");
                        String postLikes = feedsObj.getString("postLikes");
                        String postComments = feedsObj.getString("postComments");
                          
                        // adding data to our modal class.
                        FacebookFeedModal feedModal = new FacebookFeedModal(authorImage, authorName, postDate, postDescription, postIV, postLikes, postComments);
                        facebookFeedModalArrayList.add(feedModal);
                          
                        // below line we are creating an adapter class and adding our array list in it.
                        FacebookFeedRVAdapter adapter = new FacebookFeedRVAdapter(facebookFeedModalArrayList, 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) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Fail to get data with error " + error, Toast.LENGTH_SHORT).show();
            }
        });
        mRequestQueue.add(jsonObjectRequest);
    }
}

现在运行您的应用程序,并查看该应用程序的输出。

输出:

您可以在以下链接上检查项目: https : //github.com/ChaitanyaMunje/LibraryApp/tree/FacebookBranch

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!