Aruka J Aruka J - 7 months ago 16
Java Question

Where is the correct place to assign an interface listener in adapters?

Sometimes in a RecyclerView adapter it is helpful to call functions when you click on items in each row, so I defined an interface and assigned the listener like so:

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.RecyclerViewHolder> {
private List<SomeObject> mSomeObjectList;
private Context mContext;
private RowClickListener mListener;

public interface RowClickListener {
void someFunction(SomeObject someObject);
}

public MyRecyclerViewAdapter(Context context, List<SomeObject> objects) {
mContext = context;
mSomeObjectList = objects;
mListener = (RowClickListener) context;
}
//...


Is this the correct way to do it? I notice that when people assign listeners in Fragment classes they usually do it in the OnAttach method, which doesn't really seem to exist here in the case of an Adapter. What's considered the appropriate place here?

Answer

Rather defining it in Adapter i would suggest to use it in Fragment or Activity.

Define seperate class for Interface or define it in Fragment/Activity.

public class SomeActivity extends Activity implements RowClickListener
{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        .
        .
        .
        MyRecyclerViewAdapter adapter = new MyRecyclerViewAdapter(context,list,this);
    }

    @Override
    public void someFunction(SomeObject someObject){

    }
}

public interface RowClickListener {
    void someFunction(SomeObject someObject);
}

and in your adapter class

private RowClickListener mListener;

public MyRecyclerViewAdapter(Context context, List<SomeObject> objects, RowClickListener listener) {
    mContext = context;
    mSomeObjectList = objects;
    mListener = listener;
}