Interfacing Fragment and Adapter through Event-Driven Button Clicks
To communicate events between a Fragment and its associated Adapter, one can implement an interface within the Adapter class. In this scenario, a Fragment named MyListFragment contains a ListView that utilizes a customized CursorAdapter. Upon button click within the list row, a notification is required to be sent to the Fragment.
The solution involves creating an interface within the Adapter class:
public class MyListAdapter extends CursorAdapter { public interface AdapterInterface { void buttonPressed(); } ... }
Within the Fragment class (MyListFragment), implement the AdapterInterface:
public class MyListFragment extends Fragment implements AdapterInterface { @Override public void buttonPressed() { // Some action } }
To bind the Adapter and Fragment, modify the Adapter class:
public class MyListAdapter extends CursorAdapter { private AdapterInterface buttonListener; public MyListAdapter(Context context, Cursor c, int flags, AdapterInterface buttonListener) { super(context, c, flags); this.buttonListener = buttonListener; } ... }
Within the Adapter's bindView method, define the button click behavior:
@Override public void bindView(View view, Context context, Cursor cursor) { ... holder.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { buttonListener.buttonPressed(); } }); }
When creating the Adapter, pass the Fragment as an argument:
MyListAdapter adapter = new MyListAdapter(getActivity(), myCursor, myFlags, this);
This mechanism ensures that when the button is clicked, the Fragment receives the notification through the implemented interface.
The above is the detailed content of How to Communicate Between a Fragment and its Adapter using an Event-Driven Button Click?. For more information, please follow other related articles on the PHP Chinese website!