Implementing an Interface for Communication between Fragment and Adapter
In the scenario described, you have a fragment, MyListFragment, containing a ListView and a custom CursorAdapter. You aim to notify MyListFragment when a button is pressed in a specific row of the list. To achieve this communication, you can employ an interface-based approach.
In MyListAdapter, define an interface, AdapterInterface, with a callback method, buttonPressed(), to be invoked upon button click:
public class MyListAdapter extends CursorAdapter { public interface AdapterInterface { public void buttonPressed(); } ... }
Next, modify MyListAdapter to include an instance variable of type AdapterInterface and a constructor that accepts an instance of this interface as an argument:
private AdapterInterface buttonListener; public MyListAdapter (Context context, Cursor c, int flags, AdapterInterface buttonListener) { super(context,c,flags); this.buttonListener = buttonListener; }
In MyListFragment, implement AdapterInterface and override buttonPressed(), which will be invoked from the AdapterView's onClickListener in the adapter:
public MyListFragment extends Fragment implements AdapterInterface { @Override public void buttonPressed() { // ... } }
Finally, instantiate MyListAdapter within MyListFragment and pass an instance of MyListFragment itself as an argument to the adapter's constructor:
MyListAdapter adapter = new MyListAdapter (getActivity(), myCursor, myFlags, this);
By doing this, MyListAdapter can invoke the buttonPressed() method of MyListFragment whenever the button in the list row is pressed. This allows for seamless communication between the adapter and the fragment, enabling you to take the necessary actions upon button click.
The above is the detailed content of How to Communicate Between a Fragment and its Adapter Using an Interface?. For more information, please follow other related articles on the PHP Chinese website!