How to create interface between Fragment and adapter?
android, interface, java
Solution
Make a new constructor and an instance variable:
AdapterInterface buttonListener;
public MyListAdapter (Context context, Cursor c, int flags, AdapterInterface buttonListener)
{
super(context,c,flags);
this.buttonListener = buttonListener;
}
When the Adapter is made, the instance variable will be given the proper reference to hold.
To call the Fragment from the click:
public void onClick(View v) {
buttonListener.buttonPressed();
}
When making the `Adapter`, you will have to also pass your Fragment off to the Adapter. For example
MyListAdapter adapter = new MyListAdapter (getActivity(), myCursor, myFlags, this);
since `this` will refer to your Fragment, which is now an `AdapterInterface`.
Keep in mind that on orientation of the Fragment changes, it will most likely be recreated. If your Adapter isn't recreated, it can potentially keep a reference to a nonexistent object, causing errors.
Problem
I have fragment with `ListView`, say `MyListFragment`, and custom `CursorAdapter`. I'm setting `onClickListener` in this adapter for the button in the list row. ``` public class MyListAdapter extends CursorAdapter { public interface AdapterInterface { public void buttonPressed(); } ... @Override public void bindView(final View view, final Context context, final Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); ... holder.button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // some action // need to notify MyListFragment } }); } } public MyListFragment extends Fragment implements AdapterInterface { @Override public void buttonPressed() { // some action } } ``` I need to notify fragment when the button is pressed. How to invoke this interface? Help, please.