Home >Java >javaTutorial >How to Implement Communication Between a Fragment and a Custom Cursor Adapter?
Introduction:
Creating a communication channel between a fragment and a custom cursor adapter can facilitate seamless data exchange and event handling between these components.
Problem:
A fragment contains a ListView associated with a cursor adapter. The adapter features a button in each list row with an onClick listener. The goal is to notify the fragment when this button is pressed.
Solution:
Define an Interface in the Adapter:
Implement the Interface in the Fragment:
Pass the Fragment as an Argument to the Adapter:
Invoke the Interface from the Adapter's OnClickListener:
Example Code:
public class MyListAdapter extends CursorAdapter { public interface AdapterInterface { public void buttonPressed(); } private AdapterInterface buttonListener; public MyListAdapter (Context context, Cursor c, int flags, AdapterInterface buttonListener) { super(context,c,flags); this.buttonListener = buttonListener; } @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) { buttonListener.buttonPressed(); } }); } } public MyListFragment extends Fragment implements AdapterInterface { @Override public void buttonPressed() { // some action } }
Usage:
Create an instance of the adapter, passing the fragment as an argument:
MyListAdapter adapter = new MyListAdapter (getActivity(), myCursor, myFlags, this);
Caution for Orientation Changes:
The above is the detailed content of How to Implement Communication Between a Fragment and a Custom Cursor Adapter?. For more information, please follow other related articles on the PHP Chinese website!