Android Studio (java) -fragment 的 recyclerView 项目无法永久删除

问题描述 投票:0回答:1

我是在我们的项目中使用 Android Studio 的初学者。我正在尝试从永久删除的片段的 recyclerView 中获取一个项目。

这是我的

MainActivity
:

package com.example.recipeapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;

import com.example.recipeapp.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        super.onCreate(savedInstanceState);
        setContentView(binding.getRoot());
        replaceFragment(new HomeFragment());

        binding.bottomNavigationView.setOnItemSelectedListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.home) {
                replaceFragment(new HomeFragment());
            } else if (itemId == R.id.favorites) {
                replaceFragment(new FavoritesFragment());
            } else if (itemId == R.id.settings) {
                replaceFragment(new SettingsFragment());
            }

            return true;
        });
    }
    private void replaceFragment(Fragment fragment){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.frame_layout,fragment);
        fragmentTransaction.addToBackStack(null); // Add this line to add fragment to back stack
        fragmentTransaction.commit();
    }

    @Override
    public void onBackPressed() {
        // Get the fragment manager
        FragmentManager fragmentManager = getSupportFragmentManager();

        // Check if there are any fragments in the back stack
        if (fragmentManager.getBackStackEntryCount() > 0) {
            // Pop the back stack to go back to the previous fragment
            fragmentManager.popBackStack();
        } else {
            // If there are no fragments in the back stack, let the system handle the back button
            super.onBackPressed();
        }
    }
}

这是我的

Recipe
课程:

package com.example.recipeapp;

public class Recipe {
    public Recipe(int id, int foodImage, String foodTitle, String foodDesc) {
        this.id = id;
        this.foodImage = foodImage;
        this.foodTitle = foodTitle;
        this.foodDesc = foodDesc;
    }

    int id;
    int foodImage;

    public int getId() {
        return id;
    }

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

    public int getFoodImage() {
        return foodImage;
    }

    public void setFoodImage(int foodImage) {
        this.foodImage = foodImage;
    }

    public String getFoodTitle() {
        return foodTitle;
    }

    public void setFoodTitle(String foodTitle) {
        this.foodTitle = foodTitle;
    }

    public String getFoodDesc() {
        return foodDesc;
    }

    public void setFoodDesc(String foodDesc) {
        this.foodDesc = foodDesc;
    }

    String foodTitle;
    String foodDesc;
}

这是我的

RecipeAdapter
。这一点非常重要:

package com.example.recipeapp;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
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.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;

public class RecipeAdapter extends RecyclerView.Adapter<RecipeAdapter.ViewHolder> {

    private List<Recipe> recipeList;
    private Context context;
    private RecipeClickListener listener;

    public interface RecipeClickListener {
        void onFavoriteClick(Recipe recipe);
    }

    // Constructor without a RecipeClickListener
    public RecipeAdapter(Context context, List<Recipe> recipeList) {
        this.context = context;
        this.recipeList = (recipeList != null) ? recipeList : new ArrayList<>();
    }

    public RecipeAdapter(Context context, List<Recipe> recipeList, RecipeClickListener listener) {
        this.context = context;
        this.recipeList = (recipeList != null) ? recipeList : new ArrayList<>();
        this.listener = listener;
    }


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

    @Override
    public void onBindViewHolder(@NonNull RecipeAdapter.ViewHolder holder, int position) {
        int foodId = recipeList.get(position).getId();
        int foodPicture = recipeList.get(position).getFoodImage();
        String foodTitle = recipeList.get(position).getFoodTitle();
        String foodDesc = recipeList.get(position).getFoodDesc();

        holder.setData(foodId, foodPicture, foodTitle, foodDesc);
    }

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

    public Recipe getItem(int position) {
        if (position >= 0 && position < recipeList.size()) {
            return recipeList.get(position);
        }
        return null;
    }


    public void removeRecipe(Recipe recipe) {
        int position = recipeList.indexOf(recipe);
        if (position != -1) {
            recipeList.remove(position);
            notifyItemRemoved(position);
        }
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView foodImage;
        TextView foodTitle, foodDesc;
        FloatingActionButton favoritesBtn;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            foodImage=itemView.findViewById(R.id.foodImage);
            foodTitle=itemView.findViewById(R.id.foodTitle);
            foodDesc=itemView.findViewById(R.id.foodDesc);
            favoritesBtn=itemView.findViewById(R.id.favoritesBtn);
        }

        public void setData(int foodID, int image, String title, String desc){
            foodImage.setImageResource(image);
            foodTitle.setText(title);
            foodDesc.setText(desc);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(itemView.getContext(), RecipeDetails.class);
                    intent.putExtra("id", foodID);
                    itemView.getContext().startActivity(intent);

                    // Create a bundle and add recipe data
                    Bundle bundle = new Bundle();
                    bundle.putInt("foodID", foodID);
                    bundle.putInt("image", image);
                    bundle.putString("title", title);
                    bundle.putString("desc", desc);

                    // Pass the bundle to FavoritesFragment
                    FavoritesFragment favoritesFragment = new FavoritesFragment();
                    favoritesFragment.setArguments(bundle);

                }
            });

            favoritesBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Call interface method to handle click event
                    if (listener != null) {
                        int position = getAdapterPosition();
                        if (position != RecyclerView.NO_POSITION) {
                            Recipe recipe = recipeList.get(position);
                            listener.onFavoriteClick(recipe);
                        }
                    }

                    // Create a bundle and add recipe data
                    Bundle bundle = new Bundle();
                    bundle.putInt("foodID", foodID);
                    bundle.putInt("image", image);
                    bundle.putString("title", title);
                    bundle.putString("desc", desc);

                    // Pass the bundle to FavoritesFragment
                    FavoritesFragment favoritesFragment = new FavoritesFragment();
                    favoritesFragment.setArguments(bundle);

                    // Replace the current fragment with FavoritesFragment
                    FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
                    fragmentManager.beginTransaction().replace(R.id.frame_layout, favoritesFragment).commit();
                }
            });
        }
    }
}

这是我的

item_cardview.xml
favoritesBtn
所在的位置:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="20dp"
    app:cardElevation="10dp"
    android:layout_margin="8dp">

    <!-- Content inside the CardView -->
    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/ConstraintLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="parent">

        <ImageView
            android:id="@+id/foodImage"
            android:layout_width="match_parent"
            android:layout_height="175dp"
            android:layout_marginTop="8dp"
            android:scaleType="centerCrop"
            android:src="@drawable/baseline_image_24"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:layout_conversion_absoluteHeight="100dp"
            tools:layout_conversion_absoluteWidth="100dp" />

        <TextView
            android:id="@+id/foodTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="24dp"
            android:paddingTop="8dp"
            android:textColor="#000000"
            android:textSize="18sp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/foodImage"
            tools:layout_conversion_absoluteHeight="32dp"
            tools:layout_conversion_absoluteWidth="0dp" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/favoritesBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="24dp"
            android:layout_marginBottom="8dp"
            android:clickable="true"
            app:layout_constraintBottom_toBottomOf="@+id/foodTitle"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/foodImage"
            app:srcCompat="@drawable/baseline_favorite_24"
            tools:ignore="SpeakableTextPresentCheck" />

        <TextView
            android:id="@+id/foodDesc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="32dp"
            android:layout_marginBottom="16dp"
            android:paddingTop="8dp"
            android:textColor="#555555"
            android:textSize="14sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/foodTitle"
            tools:layout_conversion_absoluteHeight="27dp"
            tools:layout_conversion_absoluteWidth="0dp" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>

该应用程序的工作原理是,如果我单击 HomeFragment 中的

favoritesBtn
,它会将当前项目添加到FavoritesFragment 的 reyclerView 中。这部分代码的工作原理正如我预期的那样。

HomeFragment

package com.example.recipeapp;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends Fragment implements RecipeAdapter.RecipeClickListener {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;
    SharedPreferences sharedPreferences;
    private RecyclerView recyclerView;
    FloatingActionButton favoritesBtn;

    public HomeFragment() {
        // Required empty public constructor
    }

    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        View itemCardview = inflater.inflate(R.layout.item_cardview, container, false);

        sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);

        favoritesBtn = itemCardview.findViewById(R.id.favoritesBtn);
        recyclerView = view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));

        setupRecyclerView();

        return view;
    }

    private void setupRecyclerView() {
        List<Recipe> recipeList = createRecipeList();
        RecipeAdapter adapter = new RecipeAdapter(requireContext(), recipeList, this);
        recyclerView.setAdapter(adapter);
    }

    private List<Recipe> createRecipeList() {
        List<Recipe> recipeList = new ArrayList<>();
        recipeList.add(new Recipe(1, R.drawable.adobo_image, "Adobo", "A popular Filipino dish cooked with soy sauce, vinegar, garlic, and spices. It is often considered the national dish of the Philippines and is enjoyed by people of all ages."));
        recipeList.add(new Recipe(2, R.drawable.karekare_image, "Kare-kare", "A Filipino stew made with a rich, thick, peanut-based sauce. It often contains oxtail, beef tripe, and vegetables such as eggplant, banana blossom, and string beans. Kare-Kare is traditionally served with bagoong (fermented shrimp paste) on the side."));
        recipeList.add(new Recipe(3, R.drawable.lechon_image, "Lechon", "A whole roasted pig cooked over charcoal. It is often seasoned with a mix of spices and herbs before being roasted until the skin is crispy and golden brown. Lechon is a centerpiece dish at Filipino gatherings and celebrations."));
        recipeList.add(new Recipe(4, R.drawable.pancit_image, "Pancit", "A noodle dish stir-fried with vegetables, meat, and/or seafood. It is commonly served during special occasions such as birthdays and fiestas. There are many variations of Pancit, but some popular ones include Pancit Canton, Pancit Bihon, and Pancit Malabon."));
        recipeList.add(new Recipe(5, R.drawable.sinigang_image, "Sinigang", "A sour soup typically cooked with pork, shrimp, or fish and various vegetables such as kangkong (water spinach), radish, tomatoes, and green chili peppers. The sourness of the soup usually comes from tamarind or other souring agents like calamansi or guava."));

        return recipeList;
    }

    private void saveFavoritesToSharedPreferences(List<Recipe> favoritesList) {
        SharedPreferences.Editor editor = requireActivity().getSharedPreferences("Favorites", Context.MODE_PRIVATE).edit();
        Gson gson = new Gson();
        String jsonFavorites = gson.toJson(favoritesList);
        editor.putString("favorites", jsonFavorites);
        editor.apply();
    }

    private List<Recipe> loadFavoritesFromSharedPreferences() {
        SharedPreferences sharedPreferences = requireActivity().getSharedPreferences("Favorites", Context.MODE_PRIVATE);
        Gson gson = new Gson();
        String jsonFavorites = sharedPreferences.getString("favorites", "");
        Type type = new TypeToken<List<Recipe>>() {}.getType();
        return gson.fromJson(jsonFavorites, type);
    }

    @Override
    public void onFavoriteClick(Recipe recipe) {
        List<Recipe> favoritesList = loadFavoritesFromSharedPreferences();
        boolean isRecipeInFavorites = checkIfRecipeIsInFavorites(recipe, favoritesList);
        if (isRecipeInFavorites) {
            removeRecipeFromFavorites(recipe, favoritesList);
        } else {
            addRecipeToFavorites(recipe, favoritesList);
        }
        Objects.requireNonNull(recyclerView.getAdapter()).notifyDataSetChanged();
    }

    private boolean checkIfRecipeIsInFavorites(Recipe recipe, List<Recipe> favoritesList) {
        return favoritesList != null && favoritesList.stream().anyMatch(favoriteRecipe -> favoriteRecipe.getId() == recipe.getId());
    }

    private void addRecipeToFavorites(Recipe recipe, List<Recipe> favoritesList) {
        Log.d("HomeFragment", "Adding recipe to favorites");
        if (favoritesList == null) {
            favoritesList = new ArrayList<>();
        }
        favoritesList.add(recipe);
        saveFavoritesToSharedPreferences(favoritesList);
        Objects.requireNonNull(recyclerView.getAdapter()).notifyDataSetChanged();
    }

    private void removeRecipeFromFavorites(Recipe recipe, List<Recipe> favoritesList) {
        favoritesList.remove(recipe);
        saveFavoritesToSharedPreferences(favoritesList);
    }
}

问题出在FavoritesFragment 上。如果我点击那里的

favoritesBtn
,它应该从 recyclerView 中永久删除该项目。

FavoritesFragment

package com.example.recipeapp;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import java.lang.reflect.Type;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FavoritesFragment#newInstance} factory method to
 * create an instance of this fragment.
 *
 */
public class FavoritesFragment extends Fragment implements RecipeAdapter.RecipeClickListener {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    RecyclerView recyclerView;
    List<Recipe> favoritesList;
    SharedPreferences sharedPreferences;
    FloatingActionButton favoritesBtn;

    public FavoritesFragment() {
        // Required empty public constructor
    }

    public static FavoritesFragment newInstance(String param1, String param2) {
        FavoritesFragment fragment = new FavoritesFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_favorites, container, false);
        View itemCardview = inflater.inflate(R.layout.item_cardview, container, false);
        // Check if the context is not null before accessing SharedPreferences
        if (getContext() != null) {
            sharedPreferences = getContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
        } else {
            // Handle the case where the context is null, perhaps by logging an error
            Log.e("HomeFragment", "Context is null, cannot access SharedPreferences");
        }
        favoritesBtn = itemCardview.findViewById(R.id.favoritesBtn);
        recyclerView = view.findViewById(R.id.recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        favoritesBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(favoritesList.size() > 0){
                    Recipe removedRecipe = favoritesList.get(favoritesList.size() - 1);  // Remove the last item in favoritesList
                    removeRecipeFromFavorites(removedRecipe);
                }
            }
        });

        // Load favorites list from shared preferences
        favoritesList = loadFavoritesList();
        if (favoritesList == null) {
            favoritesList = new ArrayList<>(); // Initialize if null
        }

        // Retrieve data from bundle if available
        Bundle bundle = getArguments();
        if (bundle != null) {
            int foodID = bundle.getInt("foodID");
            int image = bundle.getInt("image");
            String title = bundle.getString("title");
            String desc = bundle.getString("desc");

            // Add or remove the new recipe to/from the favorites list
            Recipe newRecipe = new Recipe(foodID, image, title, desc);
            if (!isInFavorites(newRecipe)) {
                addRecipeToFavorites(newRecipe);
            } else {
                removeRecipeFromFavorites(newRecipe);
            }
        }

        // Set up and initialize adapter
        RecipeAdapter adapter = new RecipeAdapter(getContext(), favoritesList, this);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        return view;
    }

    private boolean isInFavorites(Recipe recipe) {
        if (favoritesList != null) {
            for (Recipe favoriteRecipe : favoritesList) {
                if (favoriteRecipe.getId() == recipe.getId()) {
                    Log.d("FavoritesFragment", "Recipe is in favorites list");
                    return true;
                }
            }
        }
        Log.d("FavoritesFragment", "Recipe is not in favorites list");
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();
        // Load favorites list from shared preferences
        favoritesList = loadFavoritesList();
        // Refresh the RecyclerView to reflect any changes
        if (recyclerView != null && recyclerView.getAdapter() != null) {
            recyclerView.getAdapter().notifyDataSetChanged();
        }
    }

    @Override
    public void onFavoriteClick(Recipe recipe) {
        removeRecipeFromFavorites(recipe);

        // Remove the recipe from the RecyclerView
        if (recyclerView.getAdapter() != null && recyclerView.getAdapter() instanceof RecipeAdapter) {
            ((RecipeAdapter) recyclerView.getAdapter()).removeRecipe(recipe);
        }
        // Call the method to update the UI after removing the recipe
        updateUIAfterRemovingRecipe();
    }

    private boolean checkIfRecipeIsInFavorites(Recipe recipe) {
        if (favoritesList != null) {
            for (Recipe favoriteRecipe : favoritesList) {
                if (favoriteRecipe.getId() == recipe.getId()) {
                    return true;
                }
            }
        }
        return false;
    }

    private void addRecipeToFavorites(Recipe recipe) {
        Log.d("FavoritesFragment", "Adding recipe to favorites");
        if (favoritesList == null) {
            favoritesList = new ArrayList<>();
        }
        favoritesList.add(recipe);
        saveFavoritesList(favoritesList);
        if (recyclerView.getAdapter() != null) {
            recyclerView.getAdapter().notifyDataSetChanged();
        }
    }

    private void removeRecipeFromFavorites(Recipe recipe) {
        Log.d("FavoritesFragment", "Removing recipe from favorites");
        if (favoritesList != null) {
            favoritesList.remove(recipe);
            saveFavoritesList(favoritesList); // Save updated favoritesList to SharedPreferences
            if (recyclerView.getAdapter() != null) {
                ((RecipeAdapter) recyclerView.getAdapter()).removeRecipe(recipe); // Update RecyclerView
            }
        }
    }

    private List<Recipe> loadFavoritesList() {
        if (getContext() != null) {
            SharedPreferences sharedPreferences = getContext().getSharedPreferences("Favorites", Context.MODE_PRIVATE);
            Gson gson = new Gson();
            String json = sharedPreferences.getString("favoritesList", null);

            Type type = new TypeToken<ArrayList<Recipe>>() {}.getType();
            return gson.fromJson(json, type);
        } else {
            return new ArrayList<>(); // Return an empty list if context is null
        }
    }

    private void saveFavoritesList(List<Recipe> favoritesList) {
        // Convert the favoritesList to JSON using Gson
        Gson gson = new Gson();
        String favoritesJson = gson.toJson(favoritesList);

        // Save the JSON string to SharedPreferences
        SharedPreferences.Editor editor = requireContext().getSharedPreferences("Favorites", Context.MODE_PRIVATE).edit();
        editor.putString("favoritesList", favoritesJson);
        editor.apply();
    }

    // After removing the recipe from the list in FavoritesFragment, you can update the UI as follows:

    // Add a method in FavoritesFragment to update the UI after removing a recipe
    private void updateUIAfterRemovingRecipe() {
        if (getActivity() != null) {
            // Refresh the RecyclerView to reflect the changes
            if (recyclerView.getAdapter() != null) {
                recyclerView.getAdapter().notifyDataSetChanged();
            }
        }
    }
}

但是,发生的情况是,单击FavoritesFragment中的favoritesBtn后,该项目消失并再次出现。我可以真正删除当前项目的唯一方法是退出应用程序,转到应用程序信息并清除应用程序的存储,但这样做也会删除其余的项目。我能做什么?

这是演示的视频链接

java android android-fragments android-recyclerview
1个回答
0
投票
favoritesBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Call interface method to handle click event
                    if (listener != null) {
                       // int position = getAdapterPosition();
                       // if (position != RecyclerView.NO_POSITION) {
                        //    Recipe recipe = recipeList.get(position);
                        //    listener.onFavoriteClick(recipe);
                   list.remove(position);
                   notifyItemRemoved(position);
                   notifyItemRangeChanged(position, list.size());
                        }
                    }

                    // Create a bundle and add recipe data
                    Bundle bundle = new Bundle();
                    bundle.putInt("foodID", foodID);
                    bundle.putInt("image", image);
                    bundle.putString("title", title);
                    bundle.putString("desc", desc);

                    // Pass the bundle to FavoritesFragment
                    FavoritesFragment favoritesFragment = new FavoritesFragment();
                    favoritesFragment.setArguments(bundle);

                    // Replace the current fragment with FavoritesFragment
                    FragmentManager fragmentManager = ((AppCompatActivity)context).getSupportFragmentManager();
                    fragmentManager.beginTransaction().replace(R.id.frame_layout, favoritesFragment).commit();
                }
            });
        }
© www.soinside.com 2019 - 2024. All rights reserved.