Сохранение состояния CheckBox в SharedPreference при прокрутке RecyclerView - PullRequest
0 голосов
/ 10 июля 2020

Есть приложение, использующее список RecyclerView. В этом списке есть CheckBox, при нажатии на который элемент сохраняется в «избранном». Сохранение происходит с использованием SharedPreference, и значения флагов сохраняются даже после перезапуска приложения. Но вам просто нужно прокручивать вверх и вниз - значения удаляются (я знаю, что причина этого в том, что RecyclerView повторно использует элементы). Как сохранить эти флаги при прокрутке?

CatalogAdapter

public class CatalogAdapter extends RecyclerView.Adapter<CatalogAdapter.CatalogViewHolder> {

Context context;
ArrayList<Item> arrayList;

public CatalogAdapter(Context context, ArrayList<Item> arrayList) {
    this.context = context;
    this.arrayList = arrayList;
}

@NonNull
@Override
public CatalogViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
    return new CatalogViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull CatalogViewHolder holder, int position) {
    Item item = arrayList.get(position);

    holder.title.setText(item.getTitle());
    holder.text.setText(item.getBrand());
    holder.price.setText(String.valueOf(item.getPrice()));

    Picasso.with(context)
            .load(item.getImageLink())
            .into(holder.imageView);

    holder.favorites.isChecked();
    //holder.favorites.setChecked(loadSP(String.valueOf(position)));
    holder.favorites.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (holder.favorites.isChecked()) {
                saveSP(String.valueOf(position), true);
                Toast.makeText(context, "Добавлено", Toast.LENGTH_SHORT).show();
            }
            else {
                deleteSp(String.valueOf(position));
                Toast.makeText(context, "Удалено", Toast.LENGTH_SHORT).show();
            }
        }
    });


}

@Override
public int getItemCount() {
    return arrayList.size();
}


public static class CatalogViewHolder extends RecyclerView.ViewHolder {
    ImageView imageView;
    CheckBox favorites;
    TextView title, text, price;

    public CatalogViewHolder(@NonNull View itemView) {
        super(itemView);
        imageView = itemView.findViewById(R.id.imageViewItem);
        title = itemView.findViewById(R.id.titleItem);
        text = itemView.findViewById(R.id.textItem);
        price = itemView.findViewById(R.id.priceItem);
        favorites = itemView.findViewById(R.id.checkbox_favorite_item);
        
    }

}

//Сохраняет флажок в SharedPreferences
public void saveSP(String key, boolean value) {
    SharedPreferences sharedPreferences = context.getSharedPreferences("Values", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean(key, value).apply();
}

//Загружает нажатый флажок из SharedPreferences
public boolean loadSP(String key) {
    SharedPreferences sharedPreferences = context.getSharedPreferences("Values", Context.MODE_PRIVATE);
    return sharedPreferences.getBoolean(key, false);
}

//Удаляет нажатый флажок из SharedPreferences
public void deleteSp(String key){
    SharedPreferences sharedPreferences = context.getSharedPreferences("Values", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.remove(key).apply();
}
}

CatalogActivity

public class CatalogActivity extends AppCompatActivity {

private RecyclerView recyclerView;
private Toolbar toolbar;
private CatalogAdapter catalogAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_catalog);

    toolbar = findViewById(R.id.toolbar_catalog);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    recyclerView = findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
    getData();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_toolbar_catalog, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home)
    //Возврат на предыдущий экран
    {
        finish();
    }
    //Переход в активити корзину
    if (id == R.id.menu_basket) {
        startActivity(new Intent(CatalogActivity.this, BasketActivity.class));
    }
    return super.onOptionsItemSelected(item);
}

//Получение данных с сервера
public void getData() {
    NetworkRequest.getRequest()
            .getTestApi()
            .getTestModel()
            .enqueue(new Callback<ArrayList<Item>>() {
                @Override
                public void onResponse(Call<ArrayList<Item>> call, Response<ArrayList<Item>> response) {
                    ArrayList<Item> item = response.body();
                    catalogAdapter = new CatalogAdapter(CatalogActivity.this, item);
                    recyclerView.setAdapter(catalogAdapter);
                }

                @Override
                public void onFailure(Call<ArrayList<Item>> call, Throwable t) {
                    Toast.makeText(CatalogActivity.this, "Безуспешно", Toast.LENGTH_SHORT).show();
                }
            });
}
}

Model class Item

public class Item {

@SerializedName("id")
@Expose
private int id;

@SerializedName("imageLink")
@Expose
private String imageLink;

@SerializedName("title")
@Expose
private String title;

@SerializedName("price")
@Expose
private int price;

@SerializedName("available")
@Expose
private boolean available;

@SerializedName("favorite")
@Expose
private boolean favorite;

@SerializedName("brand")
@Expose
private String brand;


public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getImageLink() {
    return imageLink;
}

public void setImageLink(String imageLink) {
    this.imageLink = imageLink;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public int getPrice() {
    return price;
}

public void setPrice(int price) {
    this.price = price;
}

public boolean isAvailable() {
    return available;
}

public void setAvailable(boolean available) {
    this.available = available;
}

public boolean isFavorite() {
    return favorite;
}

public void setFavorite(boolean favorite) {
    this.favorite = favorite;
}

public String getBrand() {
    return brand;
}

public void setBrand(String brand) {
    this.brand = brand;
}
}
...