RecyclerView Has An Instance For Each Item Of A List
Solution 1:
You have just saved the position of the selected item but not the state of all the items in the list i.e whether they are selected or unselected. Recycler View recycles the views when scrolled. So, you just need to use ArrayList of PlanelModel instead of ArrayList of String as shared below which has a variable called "isPlanetSelected" to save state of the item.
public class PlanetModel {
private String planetName;
private boolean isPlanetSelected;
public String getPlanetName() {
return planetName;
}
public void setPlanetName(String planetName) {
this.planetName = planetName;
}
public boolean isPlanetSelected() {
return isPlanetSelected;
}
public void setPlanetSelected(boolean planetSelected) {
isPlanetSelected = planetSelected;
}
}
Make following changes in your PlanetAdapter class:
ArrayList of PlanetModel instead of String:
private ArrayList<PlanetModel> episodeslist;
In onBindViewHolder set name of the episode as:
tv.setText(episodeslist.get(position).getPlanetName());
In onBindViewHolder set selected state of the view:
if (episodeslist.get(position).isPlanetSelected()) {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryDark));
}else{
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryLight));
}
Also, update the isPlanetSelected for that particular index
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
for (int i=0; i<mEpisodes.length; i++)
{
mEpisodes.get(i).setIsPlanetSelected(false);
}
mEpisodes.get(position).setIsPlanetSelected(true);
//notify your recycler views adaper
}
});
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { episodeslist.get(position).setPlanetSelected(true) } });
Don't forget to set planet selected false wen it is unselected
episodeslist.get(position).setPlanetSelected(false)
Both your issues will be resolved with above approach.
Thanks.
Post a Comment for "RecyclerView Has An Instance For Each Item Of A List"