Created
March 25, 2019 20:56
-
-
Save mitchtabian/c795c12211d52ea0c65c7c5a56910358 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyViewHolder> { | |
private static final String TAG = "RecyclerAdapter"; | |
private List<Post> posts = new ArrayList<>(); | |
@NonNull | |
@Override | |
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { | |
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_post_list_item, null, false); | |
return new MyViewHolder(view); | |
} | |
@Override | |
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) { | |
holder.bind(posts.get(position)); | |
} | |
@Override | |
public int getItemCount() { | |
return posts.size(); | |
} | |
public void setPosts(List<Post> posts){ | |
this.posts = posts; | |
notifyDataSetChanged(); | |
} | |
public void updatePost(Post post){ | |
posts.set(posts.indexOf(post), post); | |
notifyItemChanged(posts.indexOf(post)); | |
} | |
public List<Post> getPosts(){ | |
return posts; | |
} | |
public class MyViewHolder extends RecyclerView.ViewHolder{ | |
TextView title, numComments; | |
ProgressBar progressBar; | |
public MyViewHolder(@NonNull View itemView) { | |
super(itemView); | |
title = itemView.findViewById(R.id.title); | |
numComments = itemView.findViewById(R.id.num_comments); | |
progressBar = itemView.findViewById(R.id.progress_bar); | |
} | |
public void bind(Post post){ | |
title.setText(post.getTitle()); | |
if(post.getComments() == null){ | |
showProgressBar(true); | |
numComments.setText(""); | |
} | |
else{ | |
showProgressBar(false); | |
numComments.setText(String.valueOf(post.getComments().size())); | |
} | |
} | |
private void showProgressBar(boolean showProgressBar){ | |
if(showProgressBar) { | |
progressBar.setVisibility(View.VISIBLE); | |
} | |
else{ | |
progressBar.setVisibility(View.GONE); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment