从附加的 RecyclerView.Adapter 调用 Fragment 方法

pro*_*cra 6 android android-fragments android-recyclerview

我最近开始使用 Android Studio 3.1.2 和 SDK 19 编写我的第一个 Android 项目。

我的一个片段包含一个带有自定义 RecyclerView.Adapter 的 RecyclerView。在适配器通过其 ViewHolder 获取的 CardView 上,可以有一个按钮。目标是,如果按下按钮,则应调用我的片段的方法,尽管它是 Fragment 的自定义子类的实例:

请求片段

public abstract class RequestingFragment extends Fragment implements RequestCallbacks {

    public final static void startRequest(final RequestOperation, String param) {
        //this is the guy i want to call
    }

    //these are the RequestCallbacks, they're all getting called in startRequest()
    public void onSuccess(JSONObject json, String parsingkey) { }

    public void onError() { }

    public void onFinished() { }
Run Code Online (Sandbox Code Playgroud)

现在我的RequestingFragment之一包含一个 RecyclerView,其上附加了一个自定义的ErrorCompactAdapter。在 Adapters ViewHolder 中,我加载单个 CardViews 的布局,有一个按钮,它应该startRequest()从我的RequestingFragment调用onClick

ErrorCompactAdapter

public class ErrorCompactAdapter extends RecyclerView.Adapter<ErrorCompactAdapter.ErrorCompactViewHolder> {

    private Context context;
    private ArrayList<Error> errors;

    public ErrorCompactAdapter(Context context, ArrayList<Error> errors) {
        this.context = context;
        this.errors = errors;
    }
    
    public void onBindViewHolder(ErrorCompactViewHolder, int position) {
        //...
        holder.errorTakeOverButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //here's were i'm stuck
            }
        });
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

我的第一种方法是将ErrorCompactAdaptercontext属性更改为RequestingFragment,以便我可以调用它。startRequest()

private Context context; // private RequestingFragment attacher;

public void onClick(View v) {
    attacher.startRequest(/*params*/);
}
Run Code Online (Sandbox Code Playgroud)

但我非常不确定,是否包含 RecyclerView 的片段将是接收请求响应的片段,或者是否以某种方式“伪匿名”片段将接收响应,然后只是对它不做任何事情。如果这是正确的道路,有人可以启发我吗?提前致谢。

Ami*_*gid 9

在 ErrorCompactAdapter 类的构造函数中传递 Fragment。这以我想要的方式对我有用。我遇到过同样的问题。

RequestingFragment mFragment;

public ErrorCompactAdapter(Context context, ArrayList<Error> errors, 
                           RequestingFragment fragment) 
{
    this.context = context;
    this.errors = errors;
    this.mFragment = fragment;
}

// While passing the fragment into your adapter, do it this way.

ErrorCompactAdapter errorCompactAdapter = new ErrorCompactAdapter(
          context, errors, RequestingFragment.this);

holder.errorTakeOverButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // use you method of fragment here
        mFragment.startRequest();
    }
});
Run Code Online (Sandbox Code Playgroud)