Android Studio (Java) - 使用按钮将片段中的 recyclerView 的项目添加到另一个片段的 recyclerView 中

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

我是在我们的项目中使用 Android Studio 的初学者。如何将片段中的 recyclerView 项目添加到另一个包含 recyclerView 的片段中?我不知道该怎么做。现在,我可以手动将项目添加到FavoritesFragment的recyclerView的唯一方法是直接在FavoritesFragment类本身上使用

FavoriteList.add()

Recipe.java

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.java

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

    List<Recipe> RecipeList;

    public RecipeAdapter(List<Recipe> recipeList) {
        this.RecipeList = recipeList;
    }

    @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 class ViewHolder extends RecyclerView.ViewHolder {
        ImageView foodImage;
        TextView foodTitle, foodDesc;
        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);
        }

        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);
                }
            });
        }
    }
}

item_cardview.xml

<?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="150dp"
            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" />

        <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" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/favoritesBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="2dp"
            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"
            tools:layout_conversion_absoluteHeight="56dp"
            tools:layout_conversion_absoluteWidth="56dp" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>

这是我的主要活动:

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();
        }
    }
}

首页片段:

public class HomeFragment extends Fragment {
    RecyclerView recyclerView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        recyclerView = view.findViewById(R.id.recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        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."));

        RecipeAdapter adapter = new RecipeAdapter(RecipeList);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        return view;
    }
}

最爱片段:

public class FavoritesFragment extends Fragment {
    RecyclerView recyclerView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_favorites, container, false);
        recyclerView = view.findViewById(R.id.recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        List<Recipe> FavoriteList = new ArrayList<>();
        FavoriteList.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."));

        RecipeAdapter adapter = new RecipeAdapter(FavoriteList);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        return view;
    }
}

食谱详情:

public class RecipeDetails extends AppCompatActivity {
    ImageView recipeDetailsImage;
    TextView recipeDetailsTitle, recipeDetailsDesc;
    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recipe_details);

        Intent i = getIntent();
        int foodID = i.getIntExtra("id", 1);
        recipeDetailsImage = findViewById(R.id.recipeDetailsImage);
        recipeDetailsTitle = findViewById(R.id.recipeDetailsTitle);
        recipeDetailsDesc = findViewById(R.id.recipeDetailsDesc);

        String in = String.valueOf(foodID);

        switch(foodID){
            case 1: {
                recipeDetailsImage.setImageResource(R.drawable.adobo_image);
                recipeDetailsTitle.setText("Adobo");
                recipeDetailsDesc.setText("1. Marinate: Combine meat (chicken, pork, or both) with soy sauce, vinegar, garlic, onion, bay leaf, and peppercorns. Marinate for at least 30 minutes.\n" +
                        "\n" +
                        "2. Sear: Heat oil in a pot, then add marinated meat (including marinade). Brown meat on all sides.\n" +
                        "\n" +
                        "3. Simmer: Add water, bring to a boil, then reduce heat to simmer. Cover and cook until meat is tender, about 30-45 minutes.\n" +
                        "\n" +
                        "4. Season: Taste and adjust seasoning with salt and sugar if needed. Stir well.\n" +
                        "\n" +
                        "5. Serve: Transfer adobo to a serving dish and enjoy with rice.");
                Toast.makeText(RecipeDetails.this, "Adobo", Toast.LENGTH_SHORT).show();
                break;
            }
            case 2: {
                recipeDetailsImage.setImageResource(R.drawable.karekare_image);
                recipeDetailsTitle.setText("Kare-kare");
                recipeDetailsDesc.setText("1. Prepare Ingredients: Gather beef (or oxtail, tripe, or pork), vegetables (eggplant, string beans, banana blossom), ground peanuts or peanut butter, garlic, onion, annatto seeds, shrimp paste, and rice.\n" +
                        "\n" +
                        "2. Boil Meat: In a pot, boil the meat until tender. Remove scum that rises to the surface. Reserve the broth.\n" +
                        "\n" +
                        "3. Make Peanut Sauce: In a separate pan, sauté garlic and onion. Add ground peanuts or peanut butter and annatto seeds. Pour in the meat broth and simmer until thickened.\n" +
                        "\n" +
                        "4. Cook Vegetables: Blanch vegetables until tender but still crisp. Add to the peanut sauce and simmer until fully cooked.\n" +
                        "\n" +
                        "5. Season: Season the sauce with salt and pepper to taste. Adjust thickness by adding more broth or water if needed.\n" +
                        "\n" +
                        "6. Serve: Serve Kare-Kare hot with shrimp paste on the side. Enjoy with rice!");
                Toast.makeText(RecipeDetails.this, "Kare-kare", Toast.LENGTH_SHORT).show();
                break;
            }
            case 3: {
                recipeDetailsImage.setImageResource(R.drawable.lechon_image);
                recipeDetailsTitle.setText("Lechon");
                recipeDetailsDesc.setText("1. Prepare the Pig: Clean and prepare the pig by removing its internal organs and washing it thoroughly. Score the skin with a sharp knife to help it crisp up during roasting.\n" +
                        "\n" +
                        "2. Marinate the Pig: Rub the pig with a mixture of salt, pepper, garlic, and other seasonings of your choice. Let it marinate for several hours or overnight to enhance flavor.\n" +
                        "\n" +
                        "3. Roast the Pig: Spit-roast the pig over an open flame or in a roasting pit. Make sure to rotate it regularly to ensure even cooking and crispy skin. Cooking time will depend on the size of the pig.\n" +
                        "\n" +
                        "4. Baste the Pig: While roasting, baste the pig with a mixture of water, vinegar, and aromatics like garlic and bay leaves to keep it moist and flavorful.\n" +
                        "\n" +
                        "5. Check for Doneness: Use a meat thermometer to check the internal temperature of the pig. It should reach at least 165°F (74°C) in the thickest part of the meat to ensure it's fully cooked.\n" +
                        "\n" +
                        "6. Rest and Serve: Once cooked, remove the pig from the heat and let it rest for a few minutes before carving. Serve the Lechon hot with a dipping sauce made from vinegar, soy sauce, and spices.");
                Toast.makeText(RecipeDetails.this, "Lechon", Toast.LENGTH_SHORT).show();
                break;
            }
            case 4: {
                recipeDetailsImage.setImageResource(R.drawable.pancit_image);
                recipeDetailsTitle.setText("Pancit");
                recipeDetailsDesc.setText("1. Prepare Ingredients: Gather rice noodles (bihon), protein (chicken, pork, shrimp), vegetables (carrots, cabbage, bell peppers), garlic, onion, soy sauce, fish sauce, and chicken broth.\n" +
                        "\n" +
                        "2. Soften Noodles: Soak the rice noodles in warm water until they soften, then drain and set aside.\n" +
                        "\n" +
                        "3. Sauté Aromatics: In a large pan or wok, sauté minced garlic and chopped onion until fragrant.\n" +
                        "\n" +
                        "4. Cook Protein: Add the protein (chicken, pork, shrimp) and cook until browned and cooked through.\n" +
                        "\n" +
                        "5. Add Vegetables: Add julienned carrots, sliced cabbage, and other vegetables of your choice. Stir-fry until slightly softened.\n" +
                        "\n" +
                        "6. Season and Add Noodles: Season with soy sauce and fish sauce to taste. Add the softened rice noodles to the pan and toss to combine.\n" +
                        "\n" +
                        "7. Moisten with Broth: Pour in chicken broth gradually, stirring continuously, until the noodles and vegetables are fully cooked and the liquid is absorbed.\n" +
                        "\n" +
                        "8. Serve: Transfer the Pancit to a serving dish and garnish with sliced green onions and calamansi or lemon wedges. Serve hot and enjoy!");
                Toast.makeText(RecipeDetails.this, "Pancit", Toast.LENGTH_SHORT).show();
                break;
            }
            case 5: {
                recipeDetailsImage.setImageResource(R.drawable.sinigang_image);
                recipeDetailsTitle.setText("Sinigang");
                recipeDetailsDesc.setText("1. Prepare Ingredients: Gather meat (pork, beef, shrimp), vegetables (radish, eggplant, spinach), tamarind soup base or fresh tamarind, tomatoes, onions, and green chili peppers.\n" +
                        "\n" +
                        "2. Boil Meat: Boil the meat in water until tender. Skim off any foam that rises to the surface.\n" +
                        "\n" +
                        "3. Add Vegetables: Add radish and tomatoes to the pot and cook until slightly softened.\n" +
                        "\n" +
                        "4. Season with Tamarind: Add tamarind soup base or fresh tamarind to the pot to achieve the desired level of sourness.\n" +
                        "\n" +
                        "5. Add Remaining Vegetables: Add eggplant and green chili peppers to the pot and cook until all vegetables are tender.\n" +
                        "\n" +
                        "6. Season to Taste: Season with fish sauce or salt to taste. Adjust the sourness with more tamarind if needed.\n" +
                        "\n" +
                        "7. Serve: Serve Sinigang hot with steamed rice. Enjoy the tangy and savory flavors!");
                Toast.makeText(RecipeDetails.this, "Sinigang", Toast.LENGTH_SHORT).show();
                break;
            }
            default: {
                recipeDetailsImage.setImageResource(R.drawable.baseline_image_24);
                recipeDetailsTitle.setText("Title");
                recipeDetailsDesc.setText("None");
                Toast.makeText(RecipeDetails.this, in, Toast.LENGTH_SHORT).show();
                break;
            }
        }
    }
}

应该发生的情况是,在单击卡片列表上的 favoritesBtn 时,它应该将 HomeFragment 的 recyclerView 上的当前项目添加到 favoritesFragment 的 recyclerView 中。然而,目前它什么也不做。另一方面,单击卡片列表本身上的项目,将我带到 RecipeDetails 活动,该活动运行良好。这就是我的应用程序目前的样子。

java android android-fragments android-intent
1个回答
0
投票
public class FavoritesFragment extends Fragment {
    RecyclerView recyclerView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_favorites, container, false);
        recyclerView = view.findViewById(R.id.recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        List<Recipe> FavoriteList = new ArrayList<>();
        FavoriteList.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."));

        RecipeAdapter adapter = new RecipeAdapter(FavoriteList);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        return view;
    }
    public void addItem(Item item) {
    adapter.addItem(item);
     }
    }
    ---------In Home fragment-----------
    public class HomeFragment extends Fragment {
    RecyclerView recyclerView;
    private RecipeAdapter adapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        recyclerView = view.findViewById(R.id.recyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);

        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."));

        adapter = new RecipeAdapter(RecipeList);
        recyclerView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
     Button addButton = view.findViewById(R.id.addButton);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Get the selected item from the RecyclerView
                Item selectedItem = adapter.getItem(recyclerView.getChildAdapterPosition(v));
                
                // Pass the selected item to the destination fragment
                ((FavoritesFragment) getParentFragmentManager().findFragmentByTag("destination_fragment_tag"))
                        .addItem(selectedItem);
            }
        });

        return view;
    }
    }
© www.soinside.com 2019 - 2024. All rights reserved.