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.
publicclassPlanetModel {
privateString planetName;
privateboolean isPlanetSelected;
publicStringgetPlanetName() {
return planetName;
}
publicvoidsetPlanetName(String planetName) {
this.planetName = planetName;
}
publicbooleanisPlanetSelected() {
return isPlanetSelected;
}
publicvoidsetPlanetSelected(boolean planetSelected) {
isPlanetSelected = planetSelected;
}
}
Make following changes in your PlanetAdapter class:
ArrayList of PlanetModel instead of String:
privateArrayList<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
publicvoidonPageSelected(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"