将数据从RecyclerView.Adapter传递到片段onClick

时间:2019-03-28 19:16:44

标签: java android android-recyclerview fragment adapter

我试图弄清楚如何从RecyclerView中的单击项到Fragment中的列表视图获取数据。我似乎无法弄清楚该如何做,因为我无法使捆绑包正常工作。

我已经尝试了Stackoverflow上提供的各种解决方案,但是没有一个起作用。我已经设法从recyclerview获取信息,但是我一直试图找出如何将其传递给片段的方法。有人可以帮我吗?

适配器类:

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

    private Context context;

    ArrayList<FoodActivity> list;
    public FoodAdapter(ArrayList<FoodActivity> list){
        this.list = list;
    }


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

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
        holder.foods.setText(list.get(position).getName());
        holder.carbo.setText(list.get(position).getCarbohydrates());
        holder.protein.setText(list.get(position).getProtein());
        holder.fats.setText(list.get(position).getFats());

        //Get items from recyclerview when user clicks them. Then send them to FoodFragment
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String foods = list.get(position).getName();
                String carbo = list.get(position).getCarbohydrates();
                String protein = list.get(position).getProtein();
                String fats = list.get(position).getFats();

                Toast.makeText(v.getContext(), "test: " + foods, Toast.LENGTH_SHORT).show();


            }
        });
    }


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

    class ViewHolder extends RecyclerView.ViewHolder {
        TextView foods, carbo, fats, protein;

        public ViewHolder(View itemView) {
            super(itemView);

            carbo = itemView.findViewById(R.id.carbo);
            protein = itemView.findViewById(R.id.protein);
            fats = itemView.findViewById(R.id.fats);
            foods = itemView.findViewById(R.id.food);
        }
    }
}

数据来自的片段:

public class TrackingFragment extends Fragment {

    DatabaseReference databaseReference;
    ArrayList<FoodActivity> list;
    RecyclerView recyclerView;
    SearchView searchView;

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

        databaseReference = FirebaseDatabase.getInstance().getReference().child("foods");
        recyclerView = view.findViewById(R.id.rv);
        searchView = view.findViewById(R.id.searchFood);

        return view;
    }

    @Override
    public void onStart() {
        super.onStart();

        if(databaseReference != null){
            databaseReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if(dataSnapshot.exists()){
                        list = new ArrayList<>();
                        for(DataSnapshot ds : dataSnapshot.getChildren()){
                            list.add(ds.getValue(FoodActivity.class));
                        }
                        FoodAdapter adapter = new FoodAdapter(list);
                        recyclerView.setAdapter(adapter);


                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    Toast.makeText(getActivity(), databaseError.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        }
        if(searchView != null){
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    search(newText);
                    return true;
                }
            });
        }
    }

    private void search(String str){
        ArrayList<FoodActivity> searchList = new ArrayList<>();
        for(FoodActivity object : list){
            if(object.getName().toLowerCase().contains(str.toLowerCase())){
                searchList.add(object);
            }
        }
        FoodAdapter foodAdapter = new FoodAdapter(searchList);
        recyclerView.setAdapter(foodAdapter);
    }

}

以及需要去的班级:

public class FoodFragment extends Fragment {

    ImageButton addFood;

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

        addFood = view.findViewById(R.id.addFood);

        addFood.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                FragmentTransaction fr = getFragmentManager().beginTransaction();
                fr.replace(R.id.fragment_container, new TrackingFragment());
                fr.addToBackStack(null).commit();
            }
        });

        return view;
    }

}

3 个答案:

答案 0 :(得分:0)

要将数据从FoodAdapter获取到TrackingFragment,可以将TrackingFragment(或理想情况下实现的接口)作为参数添加到FoodAdapter构造函数,然后使用该实例将ViewHolder点击转发给TrackingFragment进行处理。

要将数据从TrackingFragment传输到FoodFragment,请使用setTargetFragment / onActivityResult模式进行片段<->片段通信。这个答案有一个例子:https://stackoverflow.com/a/13733914/3238938

答案 1 :(得分:0)

最简单的方法是向活动添加所需的变量,使用onClick()设置其值,然后在其他片段中检索数据:

  • 活动中:

    String foods;
    
    public String getFoods() {
        return foods;
    }
    
    public void setFoods(String foods) {
        this.foods = foods;
    }
    
  • 在适配器中:

       holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               ((YourActivity)getActivity()).setFoods("Any value");
            }
        });
    
  • 在目标片段中:

    String foods = ((YourActivity)getActivity()).getFoods();

答案 2 :(得分:0)

按如下所示向适配器添加接口

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

interface OnClickListener {
    void onClick(FoodActivity clickedItem);
}

private OnClickListener mCallback; 
private ArrayList<FoodActivity> list;

public FoodAdapter(ArrayList<FoodActivity> list){
    this.list = list;
}

public void setOnClickListener(OnClickListener callback) {
    mCallback = callback;
}


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

    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
    holder.foods.setText(list.get(position).getName());
    holder.carbo.setText(list.get(position).getCarbohydrates());
    holder.protein.setText(list.get(position).getProtein());
    holder.fats.setText(list.get(position).getFats());

    //Get items from recyclerview when user clicks them. Then send them to FoodFragment
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mCallback != null)
                mCallback.onClick(list.get(position));
        }
    });
}


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

class ViewHolder extends RecyclerView.ViewHolder {
    TextView foods, carbo, fats, protein;

    public ViewHolder(View itemView) {
        super(itemView);

        carbo = itemView.findViewById(R.id.carbo);
        protein = itemView.findViewById(R.id.protein);
        fats = itemView.findViewById(R.id.fats);
        foods = itemView.findViewById(R.id.food);
    }
}
}