android-fragments 如何从适配器内部访问getParentFragmentManager()

nue99wik  于 2022-11-14  发布在  Android
关注(0)|答案(1)|浏览(160)

我试图从一个recyclerView适配器发送一个一次性数据到一个片段,以检查哪个按钮被按下。根据官方文档,这种情况下,最好使用getParentFragmentManager()方法与片段交互,但我只能从片段访问它,而不是从适配器这里是我的适配器代码的副本:

public class MusclesListAdapter extends RecyclerView.Adapter<MusclesListAdapter.MuscleViewHolder> {
private Context context;
private List<MusclesKeys> musclesKeysList;

public MusclesListAdapter(Context context, List<MusclesKeys> musclesKeysList) {
    this.context = context;
    this.musclesKeysList = musclesKeysList;
}

@NonNull
@Override
public MuscleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View view = inflater.inflate(R.layout.muscle_group_row, parent, false);
    return new MuscleViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull MuscleViewHolder holder, int position) {
    holder.muscleBtn.setImageResource(musclesKeysList.get(position).image);
    holder.muscleBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MusclesFragment frg = new MusclesFragment();
            ExercisesFragment fragment = new ExercisesFragment();
            AppCompatActivity activity = (AppCompatActivity) view.getContext();
            Bundle bundle = new Bundle();
            bundle.putString("muscleName", musclesKeysList.get(position).getKey().toString());
            frg.getParentFragmentManager().setFragmentResult("muscleKey", bundle);
            activity.getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragmentContainerView, fragment, null).addToBackStack(null).commit();
        }
    });

}

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

public class MuscleViewHolder extends RecyclerView.ViewHolder {
    ImageView muscleBtn;

    public MuscleViewHolder(@NonNull View itemView) {
        super(itemView);
        muscleBtn = itemView.findViewById(R.id.muscle_btn);

    }
}

这是我的接收片段代码的副本:

public class ExercisesFragment extends Fragment {
private List<ExercisesKeys> exercisesList;
private RecyclerView recyclerView;
private String muscleKey;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_exercises, container, false);

    exercisesList = new ArrayList<>();
    recyclerView = v.findViewById(R.id.exercises_rv);
    recyclerView.setLayoutManager(new LinearLayoutManager(container.getContext()));
    recyclerView.setHasFixedSize(true);
    getParentFragmentManager().setFragmentResultListener("muscleKey", this, new FragmentResultListener() {
        @Override
        public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle result) {
            muscleKey = result.getString("muscleName");
        }
    });
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
    switch (muscleKey){
        case "pecs":
            databaseReference.child("pecs");
            databaseReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    exercisesList.clear();
                    for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                        ExercisesKeys exercisesKeys = new ExercisesKeys(dataSnapshot.getValue().toString());
                        exercisesList.add(exercisesKeys);
                    }
                    ExercisesListAdapter adapter = new ExercisesListAdapter(container.getContext(), exercisesList);
                    recyclerView.setAdapter(adapter);
                    adapter.notifyDataSetChanged();

                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                    Toast.makeText(container.getContext(), "fail0", Toast.LENGTH_SHORT).show();
                }
            });

        case  "shoulders":
            databaseReference.child("shoulders");
            databaseReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    exercisesList.clear();
                    for (DataSnapshot dataSnapshot : snapshot.getChildren()) {
                        ExercisesKeys exercisesKeys = new ExercisesKeys(dataSnapshot.getValue().toString());
                        exercisesList.add(exercisesKeys);
                    }
                    ExercisesListAdapter adapter = new ExercisesListAdapter(container.getContext(), exercisesList);
                    recyclerView.setAdapter(adapter);
                    adapter.notifyDataSetChanged();

                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                    Toast.makeText(container.getContext(), "fail0", Toast.LENGTH_SHORT).show();
                }
            });
    }

    return v;
}

我已经尝试通过创建适配器片段的示例来访问该方法,如您所见,尽管它确实给予我访问该方法,但每次使用应用程序时,它都会崩溃,并出现此错误
您可以在这里找到您想要的任何信息。

oug3syen

oug3syen1#

使用界面

interface MusclesListAdapteListener {
    void onClickItem();
}

将参数添加到构造函数适配器中,同时添加适配器中全局变量

MusclesListAdapteListener musclesListAdapteListener;
   public MusclesListAdapter(MusclesListAdapteListener musclesListAdapteListener , List<MusclesKeys> musclesKeysList) {
     this.musclesListAdapteListener = musclesListAdapteListener;
   }

在您的onbindviewholder中更改单击侦听器

holder.muscleBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          musclesListAdapteListener.onClickItem();
        }
}

且您片段必须实现此接口

public class ExercisesFragment extends Fragment implements MusclesListAdapteListener {

  @Override
  void onClickItem() {
      //here your code to open fragment or what do you need
  }
}

还要修改创建适配器示例代码,如下所示

ExercisesListAdapter adapter = new ExercisesListAdapter(this, exercisesList);

相关问题