Home  >  Article  >  Java  >  How to Establish Communication Between a Fragment and its CursorAdapter?

How to Establish Communication Between a Fragment and its CursorAdapter?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-12 22:10:02887browse

How to Establish Communication Between a Fragment and its CursorAdapter?

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

  • Ensure that the adapter is also recreated when the fragment is recreated to avoid referencing nonexistent objects.
  • This approach provides a clean and organized way to handle communication between the adapter and fragment.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn