Creating an Interface between Fragment and Adapter
When dealing with a fragment containing a ListView and a custom CursorAdapter, establishing communication between them becomes crucial. To achieve this, interfaces can provide a clean and efficient solution.
Interface Definition
In the adapter class, define an interface that defines the method to be invoked when the button is pressed. For example:
public interface AdapterInterface { public void buttonPressed(); }
Adapter Implementation
Add a constructor to the adapter that initializes an instance variable for the interface:
public MyListAdapter(Context context, Cursor c, int flags, AdapterInterface buttonListener) { super(context, c, flags); this.buttonListener = buttonListener; }
In the bindView() method, when the button is clicked, call the buttonPressed() method on the interface:
@Override public void bindView(...) { ... holder.button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { buttonListener.buttonPressed(); } }); }
Fragment Implementation
Implement the AdapterInterface in the fragment class and override the buttonPressed() method:
public class MyListFragment extends Fragment implements AdapterInterface { @Override public void buttonPressed() { // Custom action to be performed } }
Initialization
When creating the adapter, pass the fragment as an argument to the constructor:
MyListAdapter adapter = new MyListAdapter(getActivity(), myCursor, myFlags, this);
Notes
The above is the detailed content of How to Establish Communication Between a Fragment and its CursorAdapter?. For more information, please follow other related articles on the PHP Chinese website!