Android Studio 如何在Adapter类中调用片段?

dm7nw8vv  于 2022-11-16  发布在  Android
关注(0)|答案(1)|浏览(180)

我想调用fragment(DescDenuncia)并在(frameLayout)中替换它,我已经尝试了突出显示的行,但代码中仍缺少一些东西,我不知道为什么“getSupportFragmentManager()”行是红色的,我应该怎么做?

//Vinculando o reclycler view ao firestore
public class Adapter extends FirestoreRecyclerAdapter<Modelo, Adapter.myviewholder> {

    public Adapter(@NonNull FirestoreRecyclerOptions<Modelo> options) {
        super(options);
    }

    //Sobrescrevendo o método
    @Override
    protected void onBindViewHolder(@NonNull myviewholder holder, int position, @NonNull final Modelo model) {
        //Associando os itens do atalho ocorrências
        holder.IDText.setText(model.getID());
        holder.tipoText.setText(model.getTipo());
        Glide.with(holder.img1.getContext()).load(model.getImg()).into(holder.img1);

        ///////////////////////////////////////THE PROBLEM IS HERE///////////////////////////////////////////
        holder.RLAYOUT.setOnClickListener(new View. OnClickListener() {
            @Override
            public void onClick(View view) {

                getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, new DescDenuncia(
                )).addToBackStack(null).commit();

            }
        });
        //////////////////////////////////////////////////////////////////////////////////////////////////////
    }

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

    }

    //Coneção do reclycler view com essa classe
    public class myviewholder extends RecyclerView.ViewHolder {

        //Variáveis do modelo atalho
        TextView tipoText, IDText;
        RelativeLayout RLAYOUT;
        ImageView img1;

        //Associando os objetos ao modelo atalho
        public myviewholder(@NonNull View itemView) {
            super(itemView);

            tipoText = itemView.findViewById(R.id.txtTipo);
            img1 = itemView.findViewById(R.id.imageView);
            IDText = itemView.findViewById(R.id.txtModeloID);
            RLAYOUT = itemView.findViewById(R.id.RLlayout);
        }
    }

}
yebdmbv4

yebdmbv41#

这是因为您无法从适配器访问getSupportFragmentManager(),除非您将片段发送到适配器。在您将数据发送到适配器的位置,只需放置一个逗号,并使用'this'关键字发送片段。

recyclerView.setAdapter(new Adapter(model, this));

在适配器中创建全局片段变量:

private Fragment currentFragment = null;

然后将从发送的片段获取到适配器的片段变量,以便可以在适配器中的任何位置使用:

public Adapter(@NonNull FirestoreRecyclerOptions<Modelo> options, Fragment fragment) {
        currentFragment = fragment;
        super(options);
    }

现在您可以访问getSupportFragmentManager(),如下所示:

fragment.getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frameLayout, new DescDenuncia(
                )).addToBackStack(null).commit();

相关问题