📜  使用RecyclerView在Android中使用Shimmer进行内容占位符动画

📅  最后修改于: 2021-05-13 17:18:01             🧑  作者: Mango

我们已经看到了使用Android中的Shimmer实现内容占位符动画的简单视图。在本文中,我们将介绍如何在Android中使用带有RecyclerView的Shimmer来实现Content Placeholder Animation

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

我们将构建一个简单的应用程序,在该应用程序中,我们将仅通过API在Android RecyclerView中显示数据。为了加载数据,我们将显示一个内容占位符,以用于加载。下面提供了一个示例视频,以使您对我们在本文中将要做的事情有个大概的了解。注意,我们将使用Java语言实现该项目。

分步实施

步骤1:创建一个新项目

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

步骤2:添加使用Facebook Shimmer布局的依赖项

导航到应用程序> Gradle脚本> build.gradle文件,并将以下依赖项添加到该文件中。

现在,同步您的项目并移至XML文件。

步骤3:在Android中为互联网添加权限

导航到应用程序> AndroidManifest.xml,并在我们从Internet加载数据时为其添加权限以访问Internet。

XML


Java
public class CourseModal {
    // variables for our course
    // name and description.
    private String courseName;
    private String courseimg;
    private String courseMode;
    private String courseTracks;
  
    public String getCourseName() {
        return courseName;
    }
  
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
  
    public String getCourseimg() {
        return courseimg;
    }
  
    public void setCourseimg(String courseimg) {
        this.courseimg = courseimg;
    }
  
    public String getCourseMode() {
        return courseMode;
    }
  
    public void setCourseMode(String courseMode) {
        this.courseMode = courseMode;
    }
  
    public String getCourseTracks() {
        return courseTracks;
    }
  
    public void setCourseTracks(String courseTracks) {
        this.courseTracks = courseTracks;
    }
  
    public CourseModal(String courseName, String courseimg, String courseMode, String courseTracks) {
        this.courseName = courseName;
        this.courseimg = courseimg;
        this.courseMode = courseMode;
        this.courseTracks = courseTracks;
    }
}


XML


  
    
  
        
        
  
        
        
  
        
  
            
            
  
            
            
        
  
    
  


XML


  
    
  
        
        
  
        
        
  
        
  
            
            
  
            
            
  
        
  
    
  


XML


  
    
    
  
    
    
  
        
        
              
            
            
            
            
            
            
  
        
          
    
      


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;
  
public class CourseRVAdapter extends RecyclerView.Adapter {
      
    // creating a variable for array list and context.
    private ArrayList courseModalArrayList;
  
    public CourseRVAdapter(ArrayList courseModalArrayList, Context context) {
        this.courseModalArrayList = courseModalArrayList;
        this.context = context;
    }
  
    private Context context;
  
    @NonNull
    @Override
    public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
          
        // below line is to inflate our layout.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) {
        // setting data to our views of recycler view.
        CourseModal modal = courseModalArrayList.get(position);
        holder.courseNameTV.setText(modal.getCourseName());
        holder.courseTracksTV.setText(modal.getCourseTracks());
        holder.courseModeTV.setText(modal.getCourseMode());
        Picasso.get().load(modal.getCourseimg()).into(holder.courseIV);
    }
  
    @Override
    public int getItemCount() {
        return courseModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our views.
        private TextView courseNameTV, courseModeTV, courseTracksTV;
        private ImageView courseIV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our views with their ids.
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseModeTV = itemView.findViewById(R.id.idTVBatch);
            courseTracksTV = itemView.findViewById(R.id.idTVTracks);
            courseIV = itemView.findViewById(R.id.idIVCourse);
        }
    }
}


Java
import android.os.Bundle;
import android.view.View;
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.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.facebook.shimmer.ShimmerFrameLayout;
  
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 ui components.
    private RecyclerView courseRV;
  
    // variable for our adapter
    // class and array list
    private CourseRVAdapter adapter;
    private ArrayList courseModalArrayList;
    private ShimmerFrameLayout shimmerFrameLayout;
  
    // below line is the variable for url from
    // where we will be querying our data.
    String url = "https://jsonkeeper.com/b/WO6S";
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our variables.
        courseRV = findViewById(R.id.idRVCourses);
        shimmerFrameLayout = findViewById(R.id.shimmerLayout);
        shimmerFrameLayout.startShimmer();
          
        // below line we are creating a new array list
        courseModalArrayList = new ArrayList<>();
          
        // calling a method to load data.
        getData();
          
        // calling method to
        // build recycler view.
        buildRecyclerView();
    }
  
    private void getData() {
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
         
        // in this case the data we are getting is in the form
        // of array so we are making a json array request.
        // below is the line where we are making an json array
        // request and then extracting data from each json object.
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONArray response) {
                  
                // on below line we are stopping our shimmer
                // and making its visibility to gone.
                shimmerFrameLayout.stopShimmer();
                shimmerFrameLayout.setVisibility(View.GONE);
                  
                // on below line we are making the 
                // recycler view visibility visible.
                courseRV.setVisibility(View.VISIBLE);
                for (int i = 0; i < response.length(); i++) {
                    // creating a new json object and
                    // getting each object from our json array.
                    try {
                          
                        // we are getting each json object.
                        JSONObject responseObj = response.getJSONObject(i);
                          
                        // now we get our response from API in json object format.
                        // in below line we are extracting a string with
                        // its key value from our json object.
                        // similarly we are extracting all the strings from our json object.
                        String courseName = responseObj.getString("courseName");
                        String courseTracks = responseObj.getString("courseTracks");
                        String courseMode = responseObj.getString("courseMode");
                        String courseImageURL = responseObj.getString("courseimg");
                        courseModalArrayList.add(new CourseModal(courseName, courseImageURL, courseMode, courseTracks));
                        buildRecyclerView();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show();
            }
        });
        queue.add(jsonArrayRequest);
    }
  
    private void buildRecyclerView() {
          
        // initializing our adapter class.
        adapter = new CourseRVAdapter(courseModalArrayList, MainActivity.this);
          
        // adding layout manager
        // to our recycler view.
        LinearLayoutManager manager = new LinearLayoutManager(this);
        courseRV.setHasFixedSize(true);
          
        // setting layout manager
        // to our recycler view.
        courseRV.setLayoutManager(manager);
          
        // setting adapter to
        // our recycler view.
        courseRV.setAdapter(adapter);
    }
}


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

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

Java

public class CourseModal {
    // variables for our course
    // name and description.
    private String courseName;
    private String courseimg;
    private String courseMode;
    private String courseTracks;
  
    public String getCourseName() {
        return courseName;
    }
  
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
  
    public String getCourseimg() {
        return courseimg;
    }
  
    public void setCourseimg(String courseimg) {
        this.courseimg = courseimg;
    }
  
    public String getCourseMode() {
        return courseMode;
    }
  
    public void setCourseMode(String courseMode) {
        this.courseMode = courseMode;
    }
  
    public String getCourseTracks() {
        return courseTracks;
    }
  
    public void setCourseTracks(String courseTracks) {
        this.courseTracks = courseTracks;
    }
  
    public CourseModal(String courseName, String courseimg, String courseMode, String courseTracks) {
        this.courseName = courseName;
        this.courseimg = courseimg;
        this.courseMode = courseMode;
        this.courseTracks = courseTracks;
    }
}

步骤5:在Android中为我们的RecyclerView项目创建一个布局文件

导航到应用程序> res>布局>右键单击它>新建>布局资源文件,并将其命名为course_rv_item ,并将以下代码添加到其中。

XML格式



  
    
  
        
        
  
        
        
  
        
  
            
            
  
            
            
        
  
    
  

第6步:为我们的微光布局创建一个布局文件

导航到应用程序> res>布局>右键单击它>新建>布局资源文件,并将其命名为shimmer_layout,然后将以下代码添加到其中。

XML格式



  
    
  
        
        
  
        
        
  
        
  
            
            
  
            
            
  
        
  
    
  

步骤7:使用activity_main.xml文件

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

XML格式



  
    
    
  
    
    
  
        
        
              
            
            
            
            
            
            
  
        
          
    
      

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

导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,并将其命名为CourseRVAdapter,然后将以下代码添加到其中。在代码内部添加了注释,以更详细地了解代码。

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;
  
public class CourseRVAdapter extends RecyclerView.Adapter {
      
    // creating a variable for array list and context.
    private ArrayList courseModalArrayList;
  
    public CourseRVAdapter(ArrayList courseModalArrayList, Context context) {
        this.courseModalArrayList = courseModalArrayList;
        this.context = context;
    }
  
    private Context context;
  
    @NonNull
    @Override
    public CourseRVAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
          
        // below line is to inflate our layout.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull CourseRVAdapter.ViewHolder holder, int position) {
        // setting data to our views of recycler view.
        CourseModal modal = courseModalArrayList.get(position);
        holder.courseNameTV.setText(modal.getCourseName());
        holder.courseTracksTV.setText(modal.getCourseTracks());
        holder.courseModeTV.setText(modal.getCourseMode());
        Picasso.get().load(modal.getCourseimg()).into(holder.courseIV);
    }
  
    @Override
    public int getItemCount() {
        return courseModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our views.
        private TextView courseNameTV, courseModeTV, courseTracksTV;
        private ImageView courseIV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            // initializing our views with their ids.
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseModeTV = itemView.findViewById(R.id.idTVBatch);
            courseTracksTV = itemView.findViewById(R.id.idTVTracks);
            courseIV = itemView.findViewById(R.id.idIVCourse);
        }
    }
}

步骤9:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
import android.view.View;
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.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.facebook.shimmer.ShimmerFrameLayout;
  
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 ui components.
    private RecyclerView courseRV;
  
    // variable for our adapter
    // class and array list
    private CourseRVAdapter adapter;
    private ArrayList courseModalArrayList;
    private ShimmerFrameLayout shimmerFrameLayout;
  
    // below line is the variable for url from
    // where we will be querying our data.
    String url = "https://jsonkeeper.com/b/WO6S";
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our variables.
        courseRV = findViewById(R.id.idRVCourses);
        shimmerFrameLayout = findViewById(R.id.shimmerLayout);
        shimmerFrameLayout.startShimmer();
          
        // below line we are creating a new array list
        courseModalArrayList = new ArrayList<>();
          
        // calling a method to load data.
        getData();
          
        // calling method to
        // build recycler view.
        buildRecyclerView();
    }
  
    private void getData() {
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
         
        // in this case the data we are getting is in the form
        // of array so we are making a json array request.
        // below is the line where we are making an json array
        // request and then extracting data from each json object.
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener() {
            @Override
            public void onResponse(JSONArray response) {
                  
                // on below line we are stopping our shimmer
                // and making its visibility to gone.
                shimmerFrameLayout.stopShimmer();
                shimmerFrameLayout.setVisibility(View.GONE);
                  
                // on below line we are making the 
                // recycler view visibility visible.
                courseRV.setVisibility(View.VISIBLE);
                for (int i = 0; i < response.length(); i++) {
                    // creating a new json object and
                    // getting each object from our json array.
                    try {
                          
                        // we are getting each json object.
                        JSONObject responseObj = response.getJSONObject(i);
                          
                        // now we get our response from API in json object format.
                        // in below line we are extracting a string with
                        // its key value from our json object.
                        // similarly we are extracting all the strings from our json object.
                        String courseName = responseObj.getString("courseName");
                        String courseTracks = responseObj.getString("courseTracks");
                        String courseMode = responseObj.getString("courseMode");
                        String courseImageURL = responseObj.getString("courseimg");
                        courseModalArrayList.add(new CourseModal(courseName, courseImageURL, courseMode, courseTracks));
                        buildRecyclerView();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show();
            }
        });
        queue.add(jsonArrayRequest);
    }
  
    private void buildRecyclerView() {
          
        // initializing our adapter class.
        adapter = new CourseRVAdapter(courseModalArrayList, MainActivity.this);
          
        // adding layout manager
        // to our recycler view.
        LinearLayoutManager manager = new LinearLayoutManager(this);
        courseRV.setHasFixedSize(true);
          
        // setting layout manager
        // to our recycler view.
        courseRV.setLayoutManager(manager);
          
        // setting adapter to
        // our recycler view.
        courseRV.setAdapter(adapter);
    }
}

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

输出: